// ==UserScript== // @name MT论坛 // @icon https://bbs.binmt.cc/favicon.ico // @namespace https://greasyfork.org/zh-CN/scripts/401359 // @supportURL https://github.com/WhiteSevs/TamperMonkeyScript/issues // @description MT论坛效果增强,如自动签到、自动展开帖子、滚动加载评论、显示UID、自定义屏蔽、手机版小黑屋、编辑器优化、在线用户查看、便捷式图床、自定义用户标签、积分商城商品上架提醒等 // @description 更新日志: 调整PC端功能在油猴菜单中设置 // @version 2024.9.24 // @author WhiteSevs // @run-at document-start // @match *://bbs.binmt.cc/* // @exclude /^http(s|):\/\/bbs\.binmt\.cc\/uc_server.*$/ // @license GPL-3.0-only // @grant unsafeWindow // @grant GM_addStyle // @grant GM_setValue // @grant GM_getValue // @grant GM_deleteValue // @grant GM_setClipboard // @grant GM_xmlhttpRequest // @grant GM_registerMenuCommand // @grant GM_unregisterMenuCommand // @grant GM_info // @grant GM_cookie // @connect helloimg.com // @connect z4a.net // @connect kggzs.cn // @connect woozooo.com // @connect * // @require https://lf9-cdn-tos.bytecdntp.com/cdn/expire-1-M/jquery/3.6.0/jquery.min.js // @require https://unpkg.com/any-touch/dist/any-touch.umd.min.js // @require https://update.greasyfork.icu/scripts/449471/1305484/Viewer.js // @require https://update.greasyfork.icu/scripts/449512/1305485/Xtiper.js // @require https://update.greasyfork.icu/scripts/449562/1305489/NZMsgBox.js // @require https://update.greasyfork.icu/scripts/452322/1305490/js-watermark.js // @require https://update.greasyfork.icu/scripts/456607/1309371/GM_html2canvas.js // @require https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js // @require https://update.greasyfork.icu/scripts/455186/1327728/WhiteSevsUtils.js // @downloadURL https://update.greasyfork.icu/scripts/401359/MT%E8%AE%BA%E5%9D%9B.user.js // @updateURL https://update.greasyfork.icu/scripts/401359/MT%E8%AE%BA%E5%9D%9B.meta.js // ==/UserScript== (async function () { "use strict"; if (typeof unsafeWindow === "undefined") { if ( typeof globalThis.unsafeWindow !== "undefined" && globalThis.unsafeWindow != null ) { var unsafeWindow = globalThis.unsafeWindow; } else { var unsafeWindow = globalThis || window || self; } } const console = unsafeWindow.console; /** * @type {import("./../../lib/Utils").default} */ const utils = (window.Utils || Utils).noConflict(); let $jq = null; /** * @type {import("./../../lib/AnyTouch/index.umd.js")} */ let AnyTouch = window.AnyTouch; /** * @type {import("./../../lib/Viewer/index")} */ let Viewer = window.Viewer; /** * @type {import("./../../lib/js-watermark/index")} */ let Watermark = window.Watermark; /** * @type {import("./../../lib/Xtiper/index")} */ let xtip = window.xtip; let WhiteSev_GM_Cookie = new utils.GM_Cookie(); var ajax_xmlHttpRequest = (requestData) => { console.log("$jq.ajax请求的数据: ", requestData); let headers_options = {}; let headers_options_key = [ "Accept-Charset", "Accept-Encoding", "Access-Control-Request-Headers", "Access-Control-Request-Method", "Connection", "Content-Length", "Cookie", "Cookie2", "Date", "DNT", "Expect", "Host", "Keep-Alive", "Origin", "Referer", "TE", "Trailer", "Transfer-Encoding", "Upgrade", "User-Agent", "Via", ]; if (requestData.headers != null) { Array.from(headers_options_key).forEach((item) => { delete requestData.headers[item]; }); } else { requestData.headers = {}; } $jq.ajax({ url: requestData.url, type: requestData.method, data: requestData.data, timeout: requestData.timeout, dataType: requestData.responseType, headers: headers_options, success: (response) => { let resolveDetails = {}; if (typeof response === "string") { resolveDetails = { responseText: response, type: "ajax", status: 200, readyState: 4, }; } else { resolveDetails = response; } console.log("$jq.ajax的success回调", resolveDetails); requestData.onload(resolveDetails); }, error: (response, textStatus, errorThrown) => { let resolveDetails = {}; if (response.status === 200 && typeof response === "string") { resolveDetails = { responseText: response, type: "ajax", status: 200, readyState: 4, }; } else if (response.status !== 200 && typeof response === "string") { resolveDetails = { responseText: response, type: "ajax", status: 404, readyState: 4, }; } else { resolveDetails = response; } if (textStatus === "timeout") { console.error("$jq.ajax的error回调", response); requestData.ontimeout(resolveDetails); } else if (resolveDetails.status === 200) { console.log("$jq.ajax的error->success回调", response); requestData.onload(resolveDetails); } else { console.error("$jq.ajax的error回调", response); requestData.onerror(resolveDetails); } }, }); }; /** * 自定义新的popups弹窗代替popup */ const popups = { config: { mask: { zIndex: 1000000, style: `#force-mask{width:100%;height:100%;position:fixed;top:0;left:0;background:#000;opacity:.6;z-index:1000000;display:flex;align-content:center;justify-content:center;align-items:center}`, }, confirm: { zIndex: 1000100, style: `#popups-confirm .popups-confirm-cancel,#popups-confirm .popups-confirm-ok{user-select:none;width:100%!important;background:0 0!important;border-radius:unset}`, }, toast: { zIndex: 1100000, style: `.popups-toast{width:fit-content;padding:10px 16px;color:#fff;background:rgba(0,0,0,.65);position:fixed;margin:0 auto;left:0;right:0;bottom:0;border-radius:4px;font-size:14px;z-index:1100000;max-width:80vw;opacity:1;-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;-webkit-backface-visibility:hidden;backface-visibility:hidden;-webkit-font-smoothing:antialiased/subpixel-antialiased;touch-action:pan-y;-webkit-user-select:none;user-select:none;transform:translateY(160px)} .popups-toast-show{transform:translateY(-80px)!important;transition:all .2s ease 0s;-webkit-transition:all .2s ease 0s} `, }, }, /** * 初始化 */ init() { Object.keys(popups.config).forEach((key) => { let style = popups.config[key].style; if (style !== "") { GM_addStyle(style); } }); }, /** * 初始化遮罩层 * @param {number} zIndex */ initMask(zIndex) { document.documentElement.style.overflow = "hidden"; if (!$jq("#force-mask").length) { $jq("body").append($jq('
')); } else { $jq("#force-mask").html(""); } if (!zIndex) { /* 遮罩层z-index为最大的>10 */ $jq("#force-mask").css("z-index", utils.getMaxZIndex() + 10); } }, /** * 确认弹窗 * @param {string|{ * text: string, * reverse: boolean, * mask: boolean, * only: boolean, * ok: { * enable: boolean, * text: string, * callback: Function, * }, * cancel: { * enable: boolean, * text: string, * callback: Function, * }, * other: { * enable: boolean, * text: string, * callback: Function, * }, * }} paramOptions * @returns */ confirm(paramOptions) { let options = { text: "Call By popups.confirm", reverse: false /* 底部按钮倒序 */, mask: true, only: true, ok: { enable: true, text: "确定", callback: () => { popups.closeConfirm(); }, }, cancel: { enable: true, text: "取消", callback: () => { popups.closeConfirm(); }, }, other: { enable: false, text: "另一个按钮", callback: () => { popups.closeConfirm(); }, }, }; if (typeof paramOptions == "string") { options.text = paramOptions; } else { options = utils.assign(options, paramOptions); } let bottomBtnHTML = ""; let confirmHTML = ""; /* confirm层z-index为最大的>110 */ let maxZIndex = utils.getMaxZIndex() + 10; let confirmZIndex = popups.config.confirm.zIndex > maxZIndex ? popups.config.confirm.zIndex : maxZIndex + 100; if (!options.reverse) { bottomBtnHTML = `${options.cancel.text} ${options.ok.text} `; } else { bottomBtnHTML = `${options.ok.text} ${options.cancel.text} `; } confirmHTML = `
${options.text}
${bottomBtnHTML}
`; if (options.only) { this.closeConfirm(); } let jqConfirmHTML = $jq(confirmHTML); let setBottomBtn = options.ok.enable || options.cancel.enable || options.other.enable; /* 如果所有按钮都不存在的话 */ if (!setBottomBtn) { jqConfirmHTML.find("dd.b_t").remove(); } if (options.other.enable) { jqConfirmHTML.find("dd.b_t .popups-confirm-bottom-btn").after( $jq(`
${options.other.text}
`) ); jqConfirmHTML.find(".popups-confirm-other").on("click", function () { utils.tryCatch().run(options.other.callback); }); } $jq("body").append(jqConfirmHTML); jqConfirmHTML .find(`.popups-confirm-bottom-btn a:contains('${options.ok.text}')`) .on("click", () => { utils.tryCatch().run(options.ok.callback); }); jqConfirmHTML .find(`.popups-confirm-bottom-btn a:contains('${options.cancel.text}')`) .on("click", () => { utils.tryCatch().run(options.cancel.callback); }); jqConfirmHTML .find(`.popups-confirm-bottom-btn a:contains('${options.other.text}')`) .on("click", () => { utils.tryCatch().run(options.other.callback); }); if (options.mask) { this.mask(maxZIndex); } else { this.closeMask(); } return jqConfirmHTML; }, /** * 吐司 * @param {string|{ * text: string, * only: boolean, * delayTime: number, * }} paramOptions */ toast(paramOptions) { let options = { text: "Call By popups.toast", only: true, delayTime: 2000, }; if (typeof paramOptions == "string") { options.text = paramOptions; } else { for (var key in options) { if (typeof paramOptions[key] !== "undefined") { options[key] = paramOptions[key]; } } } if (options.only) { popups.closeToast(); } let toastobj = $jq( `
${options.text}
` ); $jq("body").append(toastobj); toastobj.css( "transform", `matrix(1, 0, 0, 1, 0, ${ toastobj.outerHeight() > 80 ? toastobj.outerHeight() + 80 : 80 })` ); setTimeout(() => { toastobj.addClass("popups-toast-show"); setTimeout(() => { popups.closeToast(toastobj); }, options.delayTime); }, 150); }, /** * 遮罩层 * @param {Number} zIndex */ mask(zIndex = 0) { this.initMask(); $jq("#force-mask").show(); if (zIndex !== 0) { $jq("#force-mask").css("z-index", zIndex); } }, /** * 加载形式遮罩层 */ loadingMask() { this.initMask(); $jq("#force-mask") .html( `` ) .show(); }, /** * 关闭遮罩层 */ closeMask() { $jq("#force-mask").html("").hide(); document.documentElement.style.overflow = "auto"; }, /** * 关闭吐司 * @param {HTMLElement} toastobj */ closeToast(toastobj) { if (toastobj) { toastobj.remove(); } else { $jq(".popups-toast").remove(); } }, /** * 关闭确认弹窗 */ closeConfirm() { this.closeMask(); $jq.each($jq(".popups-popmenu"), function (index, obj) { $jq(obj).remove(); }); }, }; /** * 检测dz论坛使用的模板id,判断是桌面端还是移动端,STYLEID为4是桌面端、3是移动端 * @returns {boolean} */ const envIsMobile = function () { return ( (unsafeWindow.STYLEID || window.STYLEID || (typeof STYLEID !== "undefined" && STYLEID)) === "3" ); }; /** * 对于xtip的toast优化,只能仅且出现一个toast */ const xtips = { value: [], toast: (text, options) => { xtips.value.forEach((item) => { xtip.close(item); }); xtips.value = []; let xtip_toast_id = null; if (options == null) { xtip_toast_id = xtip.msg(text); } else { xtip_toast_id = xtip.msg(text, options); } xtips.value = xtips.value.concat(xtip_toast_id); }, }; /** * 全局数据 */ const GLOBAL_DATA = { /** * 当前是否是编辑器-快捷插入UUB弹窗的点击 */ isUBBCodeInsertClick: false, /** * 已过滤的用户元素 * @type {string[]} */ isFilterUserElementList: [], }; /** * 默认数据配置 */ const DEFAULT_CONFIG = { ownCommentsFilterData: { /** * 是否处理回复评论 */ replyFlag: false, /** * 是否处理作者评论 */ avatarFlag: false, /** * 排除小于此长度的评论 */ minLength: 3, /** * 大于此长度的评论就算关键字匹配成功了也不会被排除 */ keywordLength: 8, /** * 带有指定关键字的评论将被排除 */ keywords: [], /** * 黑名单用户 * @type {string|number[]} */ userBlackList: [], /** * 白名单用户 * @type {string|number[]} */ userWhiteList: [], }, }; /** * 定义页面元素选择器 */ const DOM_CONFIG = { /** * 页面元素的一些获取 * @returns Node */ element: { /** * 下拉列表对象 * @returns {HTMLElement} */ selectBeauty: function () { return document.querySelector( DOM_CONFIG.elementQuerySelector.selectBeauty ); }, /** * 复选框对象 * @returns {HTMLElement} */ comboxSwitch: function () { return document.querySelector( DOM_CONFIG.elementQuerySelector.comboxSwitch ); }, /** * 帖子内各个人的信息节点【list】 * @returns {NodeList} */ comiisVerify: function () { return document.querySelectorAll( DOM_CONFIG.elementQuerySelectorAll.comiisVerify ); }, /** * 导读中最新、热门、精华、回复、抢沙发的各个帖子【list】 * @returns {NodeList} */ comiisForumList: function () { return document.querySelectorAll( DOM_CONFIG.elementQuerySelectorAll.comiisForumList ); }, /** * 帖子内评论,包括帖子内容主体,第一个就是主体【list】 * @returns {NodeList} */ comiisMmlist: function () { return document.querySelectorAll( DOM_CONFIG.elementQuerySelectorAll.comiisMmlist ); }, /** * 帖子内评论,包括帖子内容主体,第一个就是主体【list】 * @returns {NodeList} */ comiisPostli: function () { return document.querySelectorAll( DOM_CONFIG.elementQuerySelectorAll.comiisPostli ); }, /** * 帖子底部一栏控件 * @returns {NodeList} */ postBottomControls: function () { return document.querySelectorAll( DOM_CONFIG.elementQuerySelectorAll.postBottomControls ); }, /** * 帖子内评论列表 * @returns {NodeList} */ postListOfComments: function () { return document.querySelectorAll( DOM_CONFIG.elementQuerySelectorAll.postListOfComments ); }, /** * 帖子内评论下一页的按钮 * @returns {NodeList} */ postNextCommect: function () { return document.querySelectorAll( DOM_CONFIG.elementQuerySelectorAll.postNextCommect ); }, }, elementQuerySelector: { selectBeauty: "select.beauty-select" /* 本脚本的选择器下拉列表 */, comboxSwitch: "code.whitesevcheckbox" /* 本脚本的开关选择器 */, }, /** * 页面的元素的选择器 * @returns "div....." */ elementQuerySelectorAll: { comiisVerify: "span.comiis_verify" /* 帖子内各个人的信息节点【list】 */, comiisForumList: "li.forumlist_li" /* 导读中最新、热门、精华、回复、抢沙发的各个帖子【list】 */, comiisMmlist: ".comiis_mmlist" /* 帖子内评论,包括帖子内容主体,第一个就是主体【list】 */, comiisPostli: "div.comiis_postli.comiis_list_readimgs.nfqsqi" /* 帖子内评论,包括帖子内容主体,第一个就是主体【list】 */, postBottomControls: ".comiis_znalist_bottom.b_t.cl" /* 帖子底部一栏控件 */, postListOfComments: "div.comiis_postlist.kqide" /* 帖子内评论列表(总) */, postNextCommect: "div.comiis_page.bg_f>a:nth-child(3)" /* 帖子内评论下一页的按钮 */, }, /** * 网页地址的正则匹配规则 */ urlRegexp: { bbs: /bbs.binmt.cc/ /* 论坛 */, searchUrl: /bbs.binmt.cc\/search.php/g /* 搜索页 */, chatUrl: /home.php\?mod=space&do=pm&subop=view/g /* 聊天页 */, homeUrl: /home.php\?mod=spacecp&ac=profile&op=info/g /* 个人空间页 */, homeUrlBrief: /home.php\?mod=space/g /* 个人空间页简略url */, homeUrlWithAt: /bbs.binmt.cc\/space-uid-/g /* 个人空间页的@点进去 */, homeKmisignUrl: /bbs.binmt.cc\/(forum.php\?mod=guide&view=hot(|&mobile=2)|k_misign-sign.html)/g /* 主页和签到页链接 */, homeSpaceUrl: /bbs\.binmt\.cc\/home\.php\?mod=space&do=profile&mycenter/g /* 【我的】 个人信息页链接 */, homeSpacePCUidUrl: /space-uid-(.*?).html/ /* PC 个人空间链接uid */, replyForum: /bbs.binmt.cc\/forum.php\?mod=post&action=reply/g /* 回复的界面url */, signUrl: "" /* 签到url */, navigationUrl: /forum.php\?mod=guide(&index=1|)&view=(newthread|hot|digest|new|sofa)(&index=1|)/g /* 导读链接,包括最新、热门、精华、回复、抢沙发 */, communityUrl: /forum.php\?forumlist/ /* 社区 */, forumPost: /(bbs.binmt.cc\/thread-|bbs.binmt.cc\/forum.php\?mod=viewthread)/g /* 帖子链接 */, forumPostPC: /.*:\/\/bbs.binmt.cc\/thread.*/ /* 资料设置 */, dataSettingUrl: /mod=space&do=profile&set=comiis&mycenter=1/ /* 帖子链接-PC */, forumGuideUrl: /bbs.binmt.cc\/forum.php\?mod=guide/g /* 导读链接 */, forumPostReply: /forum.php\?mod=post&action=reply/g /* 帖子中回复的链接 */, forumPostPage: "&page=(.*)" /* 帖子链接的当前所在页 page */, forumPostPCPage: /thread-([\w]+)-|&tid=([\w]+)/i /* PC帖子链接的当前所在页 page */, forumPlateText: /休闲灌水|求助问答|逆向教程|资源共享|综合交流|编程开发|玩机教程|建议反馈/g /* 各版块名称 */, plateUrl: /bbs.binmt.cc\/forum-[0-9]{1,2}-[0-9]{1,2}.html/g /* 板块链接 */, formhash: /formhash=(.+)&/ /* 论坛账号的凭证 */, hash: /hash=(.+)&/ /* 论坛账号的凭证 */, fontSpecial: /|<\/font>|||||align=".*?"|
[\s]*
[\s]*
/g /* 帖子内特殊字体格式 */, forumPostGuideUrl: /bbs.binmt.cc\/page-[1-5].html|bbs.binmt.cc\/forum.php\?mod=guide/g /* 帖子链接和导读链接 */, MTUid: /uid=(\d+)/ /* discuz uid */, nologin: /member.php\?mod=logging&action=login(|&mobile=2)/g /* 未登录 */, kMiSignSign: "bbs.binmt.cc/k_misign-sign.html" /* 签到url */, postForum: /forum.php\?mod=post&action=newthread/ /* 发布帖子 */, editForum: /forum.php\?mod=post&action=edit/ /* 编辑帖子 */, spacePost: /home.php\?mod=space.*?type=reply/ /* 个人空间-帖子 */, forumPostParam_ptid: /&ptid=([\d]+)/i /* 帖子链接的ptid参数 */, forumPostParam_pid: /&pid=([\d]+)/i /* 帖子链接的pid参数 */, }, /** * 脚本开始执行的时间 */ gmRunStartTime: Date.now(), /** * dz论坛在cookie中保存的键所使用的的前缀 * @returns {String} */ getCookiePre() { return unsafeWindow.cookiepre; }, /** * 当前账号的uid * @returns {number} */ getUID() { return unsafeWindow.discuz_uid; }, /** * 当前账号的formhash(有延迟仅移动端) * @returns {string} */ getFormHash() { return unsafeWindow.formhash; }, /** * 获取帖子id * @param {string} url * @returns {string|undefined} */ getForumId: (url) => { let urlMatch = url.match(/thread-([\d]+)-|&tid=([\d]+)/i); let forumId = urlMatch; if (forumId) { forumId = forumId.filter(Boolean); forumId = forumId[forumId.length - 1]; } return forumId; }, /** * 根据UID获取小|中|大头像 * @param {String} uid * @param {String} size small|middle|big * @returns {string} */ getAvatar: (uid, size = "") => { return `https://bbs.binmt.cc/uc_server/avatar.php?uid=${uid}&size=${size}&ts=1`; }, /** * 方法执行的一些环境判断,如当前所在URL判断和GM_getValue值判断 * @param {Array} matchURL * @param {string} localGMKey * @returns {Boolean} */ methodRunCheck: (matchURL = [], localGMKey = "") => { let urlMatchResult = false; let localResult = false; let currentURL = window.location.href; if (localGMKey === "") { localResult = true; } else { localResult = GM_getValue(localGMKey) ? true : false; } if (matchURL.length == 0) { urlMatchResult = true; } matchURL.forEach((item) => { if (currentURL.match(new RegExp(item), "ig")) { urlMatchResult = true; } }); return localResult && urlMatchResult; }, /** * 图片预览黑名单 * 当前图片链接的主机名,匹配方式为 indexOf * 当前图片链接的路径名,匹配方式为 match */ blackListNoViewIMG: [ { hostName: "avatar-bbs.mt2.cn", pathName: "*", }, { hostName: "cdn-bbs.mt2.cn", pathName: "^(/static(/|//)image|/template)", }, { hostName: "bbs.binmt.cc", pathName: "^(/static(/|//)image|/template)", }, { hostName: "bbs.binmt.cc", pathName: "/uc_server/avatar.php", }, ], /** * 是否已设置hljs的高亮CSS * @type {boolean} */ isSetHljsCSS: false, }; /** * 检测引用库是否正确加载 */ function checkReferenceLibraries() { let libraries = [ { object: typeof AnyTouch === "undefined" ? window.AnyTouch : AnyTouch, name: "AnyTouch", url: "https://unpkg.com/any-touch/dist/any-touch.umd.min.js", }, { object: typeof Viewer === "undefined" ? window.Viewer : Viewer, name: "Viewer", url: "https://update.greasyfork.icu/scripts/449471/1305484/Viewer.js", }, { object: typeof xtip === "undefined" ? window.xtip : xtip, name: "xtip", url: "https://update.greasyfork.icu/scripts/449512/1305485/Xtiper.js", }, { object: $jq.NZ_MsgBox, jQueryConflictName: "$jq", name: "NZ_MsgBox", url: "https://update.greasyfork.icu/scripts/449562/1305489/NZMsgBox.js", }, { object: typeof Watermark === "undefined" ? window.Watermark : Watermark, name: "Watermark", url: "https://update.greasyfork.icu/scripts/452322/1305490/js-watermark.js", }, { object: typeof html2canvas === "undefined" ? window.html2canvas : html2canvas, name: "html2canvas", url: "https://update.greasyfork.icu/scripts/456607/1309371/GM_html2canvas.js", }, { object: utils, name: "utils", url: "https://update.greasyfork.icu/scripts/455186/1327728/WhiteSevsUtils.js", }, { object: typeof hljs === "undefined" ? window.hljs : hljs, name: "hljs", url: "https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js", }, ]; for (const libraryItem of libraries) { if (typeof libraryItem["object"] === "undefined") { window .GM_loadJavaScriptLibrary( libraryItem["url"], libraryItem["jQueryConflictName"] ) .then((resolve) => { if (resolve) { console.log( `check: %c ${libraryItem["name"]} %c √ 修复`, "background:#24272A; color:#ffffff", "color:#00a5ff" ); } else { console.log( `check: %c ${libraryItem["name"]} %c ×`, "background:#24272A; color:#ffffff", "color:#f90000" ); } }); } else { console.log( `check: %c ${libraryItem["name"]} %c √`, "background:#24272A; color:#ffffff", "color:#00a5ff" ); } } } const CommonFunc = { /** * hljs的smali高亮 * @param {object} hljs * @returns {object} */ hljs_smali(hljs) { var smali_instr_low_prio = [ "add", "and", "cmp", "cmpg", "cmpl", "const", "div", "double", "float", "goto", "if", "int", "long", "move", "mul", "neg", "new", "nop", "not", "or", "rem", "return", "shl", "shr", "sput", "sub", "throw", "ushr", "xor", ]; var smali_instr_high_prio = [ "aget", "aput", "array", "check", "execute", "fill", "filled", "goto/16", "goto/32", "iget", "instance", "invoke", "iput", "monitor", "packed", "sget", "sparse", ]; var smali_keywords = [ "transient", "constructor", "abstract", "final", "synthetic", "public", "private", "protected", "static", "bridge", "system", ]; return { aliases: ["smali"], contains: [ { className: "string", begin: '"', end: '"', relevance: 0, }, hljs.COMMENT("#", "$", { relevance: 0, }), { className: "keyword", variants: [ { begin: "\\s*\\.end\\s[a-zA-Z0-9]*" }, { begin: "^[ ]*\\.[a-zA-Z]*", relevance: 0 }, { begin: "\\s:[a-zA-Z_0-9]*", relevance: 0 }, { begin: "\\s(" + smali_keywords.join("|") + ")" }, ], }, { className: "built_in", variants: [ { begin: "\\s(" + smali_instr_low_prio.join("|") + ")\\s", }, { begin: "\\s(" + smali_instr_low_prio.join("|") + ")((\\-|/)[a-zA-Z0-9]+)+\\s", relevance: 10, }, { begin: "\\s(" + smali_instr_high_prio.join("|") + ")((\\-|/)[a-zA-Z0-9]+)*\\s", relevance: 10, }, ], }, { className: "class", begin: "L[^(;:\n]*;", relevance: 0, }, { begin: "[vp][0-9]+", }, ], }; }, }; /** * 脚本环境的一些兼容,比如X浏览器 * @returns true || false */ function envCheck() { let checkStatus = true; let isFailedFunction = []; console.log("正在检测脚本环境..."); if (typeof $ != "undefined") { $jq = $.noConflict( true ); /* 为什么这么写,非油猴管理器使用该脚本没有容器环境,会修改页面的jQuery */ console.log( `check: %c $jq %c √ jQuery版本:${$jq.fn.jquery}`, "background:#24272A; color:#ffffff", "color:#00a5ff" ); if ($jq.fn.jquery != "3.6.0") { console.log( "jQuery加载错误,如果是非油猴加载本脚本方式,请放到网页加载完毕后执行" ); return false; } if (typeof jQuery != "undefined") { if (jQuery.fn.jquery === "3.6.0") { /* 回复页面的jQuery失败,再试一次 */ $jq = $.noConflict(true); } console.log( `check: %c $ %c √ 网站的jQuery版本:${ $.fn ? $.fn.jquery : jQuery.fn.jquery }`, "background:#24272A; color:#ffffff", "color:#00a5ff" ); } } else { checkStatus = false; isFailedFunction = isFailedFunction.concat("jQuery"); console.log( "check: %c $ %c ×", "background:#24272A; color:#ffffff", "color:#f90000" ); } if (typeof GM_xmlhttpRequest === "undefined") { window.GM_xmlhttpRequest_isRepair = true; isFailedFunction = isFailedFunction.concat("GM_xmlhttpRequest"); console.log( `check: %c GM_xmlhttpRequest %c 修复,该函数不存在,替换成ajax`, "background:#24272A; color:#ffffff", "background:#fff;" ); window.GM_xmlhttpRequest = ajax_xmlHttpRequest; } else { window.GM_xmlhttpRequest_isRepair = false; console.log( "check: %c GM_xmlhttpRequest %c √", "background:#24272A; color:#ffffff", "color:#00a5ff" ); } var loadNetworkResource = []; window.GM_loadJavaScriptLibrary = (url, newJQuery = "") => { /* 重新引用JavaScript文件,并且可自定义jQuery引用名 */ return new Promise((resolve) => { if (loadNetworkResource.indexOf(url) != -1) { console.log("已加载该js:", url); resolve(true); } GM_xmlhttpRequest({ url: url, method: "GET", async: false, timeout: 10000, onload: (response) => { let execStatus = false; let scriptText = response.responseText; if (newJQuery != "") { scriptText = `let $ = ${newJQuery};let jQuery = ${newJQuery};\n${scriptText}`; } else if (url.includes("highlight")) { scriptText += "\n\n window.hljs = hljs"; } try { eval(scriptText); execStatus = true; loadNetworkResource = [...loadNetworkResource, url]; } catch (error) { console.log(`eval执行失败`, error); execStatus = false; } resolve(execStatus); }, onerror: () => { console.log("网络异常,加载JS失败", url); resolve(false); }, }); }); }; window.GM_asyncLoadScriptNode = (url) => { /* 异步加载JS文件 */ return new Promise((resolve) => { let tempNode = document.createElement("script"); tempNode.setAttribute("src", url); document.head.append(tempNode); tempNode.onload = () => { resolve(); }; }); }; window.GM_asyncLoadStyleSheet = (url) => { /* 异步加载CSS文件 */ if (loadNetworkResource.indexOf(url) != -1) { console.log("已加载该css:", url); return; } loadNetworkResource = loadNetworkResource.concat(url); let cssNode = document.createElement("link"); cssNode.setAttribute("rel", "stylesheet"); cssNode.setAttribute("href", url); cssNode.setAttribute("type", "text/css"); document.head.append(cssNode); }; if (typeof GM_getValue === "undefined") { window.GM_getValue = (key, defaultValue) => { let value = window.localStorage.getItem(key); if (typeof value == "string" && value.trim() != String()) { value = JSON.parse(value); } else if (defaultValue != null) { value = defaultValue; } return value; }; console.log( "check: %c GM_getValue %c √ 修复", "background:#24272A; color:#ffffff", "color:#00a5ff" ); } else { console.log( "check: %c GM_getValue %c √", "background:#24272A; color:#ffffff", "color:#00a5ff" ); } if (typeof GM_setValue === "undefined") { window.GM_setValue = (key, value) => { if (value == undefined) { value = null; } window.localStorage.setItem(key, JSON.stringify(value)); }; console.log( "check: %c GM_setValue %c √ 修复", "background:#24272A; color:#ffffff", "color:#00a5ff" ); } else { console.log( "check: %c GM_setValue %c √", "background:#24272A; color:#ffffff", "color:#00a5ff" ); } if (typeof GM_deleteValue === "undefined") { window.GM_deleteValue = (key) => { window.localStorage.removeItem(key); }; console.log( "check: %c GM_deleteValue %c √ 修复", "background:#24272A; color:#ffffff", "color:#00a5ff" ); } else { console.log( "check: %c GM_deleteValue %c √", "background:#24272A; color:#ffffff", "color:#00a5ff" ); } if (typeof GM_addStyle === "undefined") { window.GM_addStyle = (styleText) => { let cssDOM = document.createElement("style"); cssDOM.setAttribute("type", "text/css"); cssDOM.innerHTML = styleText; document.documentElement.insertBefore( cssDOM, document.documentElement.children[0] ); return cssDOM; }; console.log( "check: %c GM_addStyle %c √ 修复", "background:#24272A; color:#ffffff", "color:#00a5ff" ); } else { console.log( "check: %c GM_addStyle %c √", "background:#24272A; color:#ffffff", "color:#00a5ff" ); } if (typeof GM_setClipboard === "undefined") { window.GM_setClipboard = (text) => { utils.setClip(text); }; console.log( "check: %c GM_setClipboard %c √ 修复", "background:#24272A; color:#ffffff", "color:#00a5ff" ); } else { console.log( "check: %c GM_setClipboard %c √", "background:#24272A; color:#ffffff", "color:#00a5ff" ); } if (typeof unsafeWindow === "undefined") { window.unsafeWindow = window; console.log( "check: %c unsafeWindow %c √ 修复", "background:#24272A; color:#ffffff", "color:#00a5ff" ); } else { console.log( "check: %c unsafeWindow %c √", "background:#24272A; color:#ffffff", "color:#00a5ff" ); } if (typeof GM_cookie === "undefined") { console.log( "check: %c GM_cookie %c √ 修复,使用Utils库中的GM_Cookie", "background:#24272A; color:#ffffff", "color:#00a5ff" ); } else { WhiteSev_GM_Cookie = GM_cookie; console.log( "check: %c GM_cookie %c √", "background:#24272A; color:#ffffff", "color:#00a5ff" ); } checkReferenceLibraries(); if (checkStatus) { console.log(`脚本环境检测结果: 通过`); } else { let isFailedStr = ""; Array.from(isFailedFunction).forEach((item) => { isFailedStr += item + "、"; }); isFailedStr = isFailedStr.replace(/、$/, ""); console.log(`脚本环境检测结果: ${isFailedStr}失败`); } return checkStatus; } /** * PC端的方法 */ const pc = { $data: { /** * @type {import("../../lib/Utils/dist/types/src/UtilsGMMenu.js").GMMenu} */ menu: null, }, main() { this.$data.menu = new utils.GM_Menu({ data: [ { key: "pc-autoSignIn", text: "自动签到", }, { key: "pc-latestReleaseForumPost", text: "导航栏-新增最新发表", }, { key: "pc-guideOptimization", text: "导读-页面美化", }, { key: "pc-detectUserOnlineStatus", text: "帖子-探测用户在线状态", }, { key: "pc-postBrowsingOptimization", text: "帖子-页面美化", }, { key: "pc-post-attachmentClickReminder", text: "帖子-附件点击提醒", }, { key: "pc-post-collectionForumPost", text: "帖子-右侧悬浮工具栏-新增收藏按钮", }, { key: "pc-post-optimizationImageView", text: "帖子-图片查看优化", }, { key: "pc-post-loadNextComments", text: "帖子-自动加载下一页", }, { key: "pc-post-quickReply", text: "帖子-右侧工具栏-快捷回复", }, { key: "pc-post-showUserLevel", text: "帖子-用户信息-显示用户等级", }, { key: "pc-identifyLinks", text: "帖子-链接文字转超链接", }, ], GM_getValue, GM_setValue, GM_registerMenuCommand, GM_unregisterMenuCommand, }); /* 电脑版函数按顺序加载 */ /* 禁止自动执行的函数(这些函数在其它地方调用) */ const notRunFuncNameList = ["main"]; Object.keys(pc).forEach((funcName) => { if (typeof pc[funcName] !== "function") { return; } if (notRunFuncNameList.includes(funcName)) { return; } // pc[funcName]() utils.tryCatch().run(pc[funcName], pc); }); }, /** * 兼容PC端 popups的toast */ initPopups() { popups.toast = (text) => { if (typeof text == "string") { xtips.toast(text); } else { xtips.toast(text.text, { times: text.delayTime ? text.delayTime / 1000 : 2, }); } }; }, /** * 附件点击提醒 */ attachmentClickReminder() { if (!this.$data.menu.getEnable("pc-post-attachmentClickReminder")) { return; } if (!window.location.href.match(DOM_CONFIG.urlRegexp.forumPost)) { return; } /** * 处理元素内的a标签的点击 * @param {HTMLElement} item */ function handleClick(item) { if (item.hasAttribute("href")) { let attachmentId = item.hasAttribute("id") ? item.id : item.parentElement.id; let attachmentURL = item.getAttribute("href"); let attachmentName = item.innerText; let attachmentMenu = document.querySelector(`#${attachmentId}_menu`); if (attachmentMenu.innerText.indexOf("金币") === -1) { return; } console.log("发现附件", item); console.log("该附件是金币附件,拦截!"); item.setAttribute("data-href", attachmentURL); item.style.setProperty("cursor", "pointer"); item.removeAttribute("href"); item.innerText = "【已拦截】" + attachmentName; item.onclick = function () { $jq.NZ_MsgBox.confirm({ title: "提示", showIcon: true, content: `
确定花费2金币下载附件 ${attachmentName}

`, type: "warning", callback: function () { console.log(attachmentURL); window.open(attachmentURL, "_blank"); }, }); }; } } utils.mutationObserver(document.documentElement, { callback: () => { document.querySelectorAll(".attnm a").forEach((item) => { handleClick(item); }); document.querySelectorAll(".comiis_attach a").forEach((item) => { handleClick(item); }); document.querySelectorAll("span[id*=attach_] a").forEach((item) => { handleClick(item); }); }, config: { childList: true, subtree: true }, }); utils.waitNodeList(".attnm a").then((nodeList) => { nodeList.forEach((item) => { handleClick(item); }); }); utils.waitNodeList(".comiis_attach a").then((nodeList) => { nodeList.forEach((item) => { handleClick(item); }); }); utils.waitNodeList("span[id*=attach_] a").then((nodeList) => { nodeList.forEach((item) => { handleClick(item); }); }); }, /** * 右侧工具栏-悬浮按钮-添加收藏帖子功能 */ collectionForumPost() { if (!window.location.href.match(DOM_CONFIG.urlRegexp.forumPost)) { return; } var own_formhash = document.querySelector( "#scform > input[type=hidden]:nth-child(1)" ).value; var collect_href_id = window.location.href .match(DOM_CONFIG.urlRegexp.forumPostPCPage) .filter(Boolean); collect_href_id = collect_href_id[collect_href_id.length - 1]; var collect_href = `https://bbs.binmt.cc/home.php?mod=spacecp&ac=favorite&type=thread&id=${collect_href_id}&formhash=${own_formhash}`; var new_collect = document.createElement("span"); var old_Suspended = document.querySelector("#scrolltop"); new_collect.innerHTML = ` `; old_Suspended.insertBefore(new_collect, old_Suspended.children[0]); }, /** * 探测用户在线状态 */ detectUserOnlineStatus() { if (!this.$data.menu.getEnable("pc-detectUserOnlineStatus")) { return; } if (!window.location.href.match(DOM_CONFIG.urlRegexp.forumPostPC)) { return; } console.log("探测用户在线状态"); var quanju = []; var cishu = 0; var favatar = document.querySelectorAll(".pls.favatar"); for (var index = 0; index < favatar.length; index++) { var sendMessage = favatar[index].getElementsByClassName("comiis_o cl"); if (sendMessage.length !== 0) { var sendmessageurl = sendMessage[0].getElementsByTagName("a")[1].href; let xhr = new XMLHttpRequest(); xhr.open("GET", sendmessageurl, false); xhr.onreadystatechange = function () { if (xhr.readyState == 4) { let pattern = /正在.*]/g; let str = xhr.responseText; let newstr = str.match(pattern)[0]; quanju.push(newstr); } }; xhr.send(); let offLineStaus = quanju[cishu].match("离线") ? true : false; cishu = cishu + 1; var onlineStatusImage = document.createElement("img"); onlineStatusImage.src = offLineStaus ? "https://cdn-bbs.mt2.cn/static/image/smiley/doge/54.png" : "https://cdn-bbs.mt2.cn/static/image/smiley/doge/35.png"; onlineStatusImage.smilied = offLineStaus ? "1353" : "1384"; onlineStatusImage.border = "0"; onlineStatusImage.style = "float:right"; favatar[index].insertAdjacentElement("afterbegin", onlineStatusImage); } } }, /** * 导读浏览优化 */ guideOptimization() { if (!this.$data.menu.getEnable("pc-guideOptimization")) { return; } if (!window.location.href.match(DOM_CONFIG.urlRegexp.forumGuideUrl)) { return; } GM_addStyle(` table>tbody[id^=normal]>tr{display:none} .xst{font-size:15px} td.author_img{width:50px;padding:15px 0} td.author_img img{width:40px;height:40px;border-radius:50%} .list_author{margin-top:2px;color:#999;font-size:12px} .bankuai_tu_by a{color:#999!important} .bankuai_tu_by img{height:16px;margin:1px 1px 0 0;vertical-align:top} tbody a:hover{text-decoration:none;color:#3498db} .byg_th_align em+a{margin-right:5px} `); let forumList = $jq(".bm_c table tbody"); forumList.each((index, item) => { let tableNode = $jq(item); let forumListTr = tableNode.find("tr"); let commonHTML = tableNode.find("th.common").html(); let forumUrl = tableNode .find("th.common")[0] .querySelectorAll("a")[0] .getAttribute("href"); let mid = null; let uid = tableNode .find("td.by>cite>a")[0] .getAttribute("href") .match(/uid-(\d+)/)[1]; let newHTML = `
${commonHTML}
作者:  ${tableNode.find("td.by>cite>a")[0].innerHTML} ${tableNode.find("td.by>em>span")[0].innerHTML}    |    最后发表:  ${ tableNode.find("td.by>cite>a")[1].innerHTML }    ${tableNode.find("td.by>em>a")[0].innerHTML} ${ tableNode.find("td.num>a")[0].innerText }   ${ tableNode.find("td.num>em")[0].innerText }
`; let newListNode = $jq(newHTML); $jq(newListNode.find(".byg_th_align")[0].children[0]).before( `[${tableNode.find("tr>td.by>a")[0].outerHTML}]` ); tableNode.html(newListNode); }); }, /** * 贴内图片查看优化 */ imageViewingOptimizationInThePost() { if (!this.$data.menu.getEnable("pc-post-collectionForumPost")) { return; } if (!window.location.href.match(DOM_CONFIG.urlRegexp.forumPost)) { return; } let handling = false; function viewIMG(imgList = [], _index_ = 0) { /* 查看图片 */ let viewerULNodeHTML = ""; imgList.forEach((item) => { viewerULNodeHTML += `
  • `; }); let viewerULNode = $jq(`
      ${viewerULNodeHTML}
    `)[0]; let viewer = new Viewer(viewerULNode, { inline: false, url: "data-src", zIndex: utils.getMaxZIndex() + 100, hidden: () => { viewer.destroy(); }, }); viewer.view(_index_); viewer.zoomTo(1); viewer.show(); } function run() { document.querySelectorAll("#postlist .comiis_vrx").forEach((item) => { let clickShowIMGList = []; /* 点击显示的图片组 */ item.querySelectorAll("img").forEach((_item_) => { let IMG_URL = _item_.src || _item_.getAttribute("file"); /* 图片链接 */ let IMG_URL_HOSTNAME = new URL(IMG_URL).hostname; /* 主机名 */ let IMG_URL_PATHNAME = new URL(IMG_URL).pathname; /* 路径 */ let imgParentNode = _item_.parentElement; /* img标签的父元素 */ if ( imgParentNode.nodeName.toLowerCase() === "a" && imgParentNode.getAttribute("href") === IMG_URL ) { imgParentNode.setAttribute("href", "javascript:;"); imgParentNode.removeAttribute("target"); } let isMatching = false; for (let item of DOM_CONFIG.blackListNoViewIMG) { /* 图片黑名单 */ if ( IMG_URL_HOSTNAME.indexOf(item["hostName"]) != -1 && IMG_URL_PATHNAME.match(item["pathName"]) ) { isMatching = true; break; } } if (isMatching) { return; } clickShowIMGList = [...clickShowIMGList, IMG_URL]; _item_.removeAttribute("onclick"); _item_.setAttribute("onclick", ""); $jq(_item_).off("click"); $jq(_item_).on("click", function (event) { utils.preventEvent(event); let _index_ = clickShowIMGList.findIndex((_img_) => { return _img_ == IMG_URL; }); viewIMG(clickShowIMGList, _index_); }); }); }); } run(); utils.waitNode("#postlist").then((element) => { utils.mutationObserver(element, { callback: () => { if (handling) { return; } handling = true; run(); handling = false; }, config: { subtree: true, childList: true, }, }); }); }, /** * 最新发表 */ latestReleaseForumPost() { if (!this.$data.menu.getEnable("pc-latestReleaseForumPost")) { return; } var latestReleaseNode = $jq( `
  • 最新发表
  • ` ); $jq("#comiis_nv .wp.comiis_nvbox.cl ul").append(latestReleaseNode); if ( window.location.href == "https://bbs.binmt.cc/forum.php?mod=guide&view=newthread" ) { $jq("#mn_forum_10").removeClass("a"); latestReleaseNode .find("a") .css( "background", 'url("https://cdn-bbs.mt2.cn/template/comiis_mi/img/nv_a.png") repeat-x 50% -50px' ); } }, /** * 加载下一页评论 */ loadNextComments() { if (!this.$data.menu.getEnable("pc-post-loadNextComments")) { return; } if (!window.location.href.match(DOM_CONFIG.urlRegexp.forumPost)) { return; } if ($jq(".pgbtn").length == 0) { console.warn("没有找到下一页按钮"); return; } var getPageInfo = function (url) { return new Promise((resolve) => { GM_xmlhttpRequest({ url: url, method: "GET", timeout: 5000, headers: { "User-Agent": utils.getRandomPCUA(), }, responseType: "html", onload: function (response) { console.log(response); var pageHTML = utils.parseFromString(response.responseText); var nextPageBtn = pageHTML.querySelector(".pgbtn a"); pageHTML.querySelector("#postlistreply")?.remove(); pageHTML.querySelector(".bm_h.comiis_snvbt")?.remove(); resolve({ url: nextPageBtn ? nextPageBtn.getAttribute("href") : null, postlist: pageHTML.querySelector("#postlist"), pgbtn: pageHTML.querySelector(".pgbtn"), pgs: pageHTML.querySelector(".pgs.mtm"), }); }, onerror: function (response) { console.error(response); popups.toast("请求异常"); resolve(false); }, ontimeout: function () { popups.toast("请求超时"); resolve(false); }, }); }); }; var isElementInViewport = function (el) { // 获取元素是否在可视区域 var doc = document.documentElement; var rect = el.getBoundingClientRect(); return ( rect.top >= 0 && rect.bottom <= (window.innerHeight || doc.clientHeight) ); }; var isHandling = false; var scrollEvent = async function () { if (isHandling == true) { return; } isHandling = true; var isElementInViewportStatus = isElementInViewport($jq(".pgbtn")[0]); if (isElementInViewportStatus) { var nextURL = $jq(".pgbtn a").attr("href"); if (nextURL) { let pageInfo = await getPageInfo(nextURL); console.log(pageInfo); if (pageInfo) { if (!pageInfo["url"]) { console.log("最后一页,取消监听"); $jq(document).off("scroll", scrollEvent); $jq(".pgbtn")?.remove(); } if (pageInfo["postlist"]) { $jq("#postlist")?.html( $jq("#postlist")?.html() + $jq(pageInfo["postlist"]).html() ); } if (pageInfo["pgbtn"]) { $jq(".pgbtn")?.html($jq(pageInfo["pgbtn"]).html()); } if (pageInfo["pgs"]) { $jq(".pgs.mtm")?.html($jq(pageInfo["pgs"]).html()); } pc.postBrowsingOptimization(); } } else { console.error("获取下一页失败"); } } await utils.sleep(50); isHandling = false; }; $jq(document).on("scroll", scrollEvent); }, /** * 帖子浏览优化 */ postBrowsingOptimization() { if (!this.$data.menu.getEnable("pc-postBrowsingOptimization")) { return; } if (!window.location.href.match(DOM_CONFIG.urlRegexp.forumPost)) { return; } let optimizationCSS = ` .pls .avatar img, .avtm img{ border-radius: 10%; } .pls .avatar img{ width: 90px; } `; /* 优化的CSS */ GM_addStyle(optimizationCSS); document.querySelectorAll("#postlist .comiis_vrx").forEach((item) => { let leftTdNode = item.querySelector( "table.plhin tr:first-child td.pls" ); let rightTdNode = item.querySelector( "table.plhin tr:first-child td.plc" ); let leftInfoMeta = leftTdNode.querySelector(".tns.xg2"); /* 左边的信息块 */ let leftInfoMetaNextElement = leftInfoMeta.nextElementSibling; /* 下一个元素 */ while (1) { if (leftInfoMetaNextElement == null) { break; } leftInfoMetaNextElement.style.display = "none"; leftInfoMetaNextElement = leftInfoMetaNextElement.nextElementSibling; } }); GM_addStyle(` .hljs{text-align:left} .hljs ol{margin:0 0 0 10px;padding:10px 10px} .hljs li{padding-left:10px;list-style-type:decimal-leading-zero;font-family:Monaco,Consolas,'Lucida Console','Courier New',serif;font-size:12px;line-height:1.8em} .hljs li:hover{background:#2c313c} .hljs li::marker{unicode-bidi:isolate;font-variant-numeric:tabular-nums;text-transform:none;text-indent:0!important;text-align:start!important;text-align-last:start!important} .hljs em[onclick^=copycode]{color:#fff;background:#246fff;margin:5px 10px;border-radius:3px;padding:0 5px;cursor:pointer;height:32px;line-height:32px;display:inline-flex} .hljs .code-select-language{height:32px;line-height:32px;font-size:14px;border:1px solid #5c5c5c;border-radius:5px;text-align:center;outline:0} `); $jq(document.head).append( $jq( `` ) ); unsafeWindow.hljs = hljs; hljs.registerLanguage("smali", CommonFunc.hljs_smali); let funcLock = new utils.LockFunction( () => { function setElementHighlight(ele, language = "java") { if (!ele.oldValue) { ele.oldValue = ele.textContent; } ele.innerHTML = hljs .highlight(ele.oldValue, { language: language }) .value.replace(/\\n$/gi, ""); } document .querySelectorAll("em[onclick^=copycode]") .forEach((coypCodeElement) => { if ( coypCodeElement.nextElementSibling && typeof coypCodeElement.nextElementSibling.className === "string" && coypCodeElement.nextElementSibling.className == "code-select-language" ) { return; } let codeLanguage = hljs.highlightAuto( coypCodeElement.parentElement.querySelector("div[id^=code]") .textContent ).language; let selectElement = document.createElement("select"); let selectLanguageList = hljs.listLanguages().sort(); selectLanguageList = selectLanguageList.concat("自动检测"); let selectInnerHTML = ""; selectLanguageList.forEach((languageName) => { if (languageName.startsWith("自动检测")) { selectInnerHTML += ``; } else { selectInnerHTML += ``; } }); selectElement.className = "code-select-language"; selectElement.innerHTML = selectInnerHTML; selectElement.addEventListener("change", function () { let changeCodeLanguage = this.selectedOptions[0].getAttribute("data-value"); console.log("切换代码块语言: ", changeCodeLanguage); this.parentElement .querySelectorAll("li") .forEach((liElement) => { setElementHighlight(liElement, changeCodeLanguage); }); }); utils.preventEvent(selectElement, "click"); utils.preventEvent(coypCodeElement, "click"); coypCodeElement.insertAdjacentElement("afterend", selectElement); utils.dispatchEvent(selectElement, "change"); }); let blockcodeElementList = document.querySelectorAll(".blockcode"); blockcodeElementList.forEach((ele) => (ele.className = "hljs")); }, this, 500 ); utils.mutationObserver(document.documentElement, { config: { subtree: true, childList: true, }, callback() { funcLock.run(); }, }); }, /** * 快捷回复 */ quickReply() { if (!this.$data.menu.getEnable("pc-post-quickReply")) { return; } if (!window.location.href.match(DOM_CONFIG.urlRegexp.forumPost)) { return; } document.querySelector("#scrolltop > span:nth-child(2) > a").onclick = function () { showWindow("reply", this.href); setTimeout( 'document.querySelector("#moreconf").innerHTML=document.querySelector("#moreconf").innerHTML+\'\';document.querySelector("#insertspace2").onclick=function(){document.querySelector("#postmessage").value=document.querySelector("#postmessage").value+" ";}', 200 ); }; }, /** * 修复电脑版未加载的js资源 */ async repairPCNoLoadResource() { await GM_asyncLoadScriptNode( "https://cdn-bbs.mt2.cn/static/js/smilies.js?x6L", false ); await GM_asyncLoadScriptNode( "https://cdn-bbs.mt2.cn/static/js/common.js?hsy", false ); }, /** * 显示用户具体等级 */ showUserLevel() { if (!this.$data.menu.getEnable("pc-post-showUserLevel")) { return; } document.querySelectorAll(".pls.favatar").forEach((userAvatarItem) => { let userLevel = "0级"; let userInfo = userAvatarItem.querySelector("tr"); let currentLevelText = userAvatarItem.querySelector("p em").innerText; let userLevelText = document.createElement("td"); userLevelText.setAttribute("style", "border-left: 1px solid #e3e3e3;"); switch (currentLevelText) { case "幼儿园": userLevel = "1级"; break; case "小学生": userLevel = "2级"; break; case "初中生": userLevel = "3级"; break; case "高中生": userLevel = "4级"; break; case "大学生": userLevel = "5级"; break; case "硕士生": userLevel = "6级"; break; case "博士生": case "实习版主": case "版主": case "审核员": userLevel = "7级"; break; case "博士后": case "超级版主": case "网站编辑": userLevel = "8级"; break; case "管理员": case "信息监察员": userLevel = "9级"; break; } userLevelText.innerHTML = `

    ${userLevel}

    Lv`; userInfo.appendChild(userLevelText); }); }, /** * 执行手机端函数 */ runMobileFunc() { if (this.$data.menu.getEnable("pc-identifyLinks")) { utils.tryCatch().run(mobileRepeatFunc.identifyLinks, mobileRepeatFunc); } if (this.$data.menu.getEnable("pc-autoSignIn")) { utils.tryCatch().run(mobile.autoSignIn, mobile); } }, }; /** * 移动端需要重复执行的函数 */ const mobileRepeatFunc = { main() { Object.keys(mobileRepeatFunc).forEach((key) => { if (key === "main" || typeof mobileRepeatFunc[key] !== "function") { return; } utils.tryCatch().run(mobileRepeatFunc[key], this); }); unsafeWindow?.popup?.init(); }, /** * 我的屏蔽 */ ownShield() { /** * 获取屏蔽数据 */ function getShieldList() { return GM_getValue("shieldList", []); } if ( window.location.href.match(DOM_CONFIG.urlRegexp.forumGuideUrl) || window.location.href.match(DOM_CONFIG.urlRegexp.plateUrl) || window.location.href.match(DOM_CONFIG.urlRegexp.forumPost) ) { let shieldUserList = getShieldList(); /* 帖子元素列表 */ document .querySelectorAll(".comiis_forumlist .forumlist_li") .forEach((item) => { let postForumInfo = { /* 用户名 */ user: item.querySelector("a.top_user").innerText, /* 用户UID */ uid: item .querySelector("a.top_user") .href.match(DOM_CONFIG.urlRegexp.MTUid)[1] .trim(), /* 用户等级 */ level: item .querySelector("span.top_lev") .innerText.replace("Lv.", ""), /* 帖子Url */ url: item.querySelector(".mmlist_li_box a").getAttribute("href") || item .querySelector(".mmlist_li_box a") .getAttribute("data-href"), /* 帖子标题 */ title: item.querySelector(".mmlist_li_box h2 a")?.innerText, /* 帖子内容(缩略) */ content: item.querySelector(".mmlist_li_box .list_body") .innerText, /* 帖子板块 */ plate: ( item.querySelector(".forumlist_li_time a.f_d") || item.querySelector(".comiis_xznalist_bk.cl") ).innerText .replace(//g, "") .replace(/\s*/g, "") .replace(/来自/g, ""), }; if (utils.isNull(postForumInfo.plate)) { postForumInfo.plate = document.querySelector( "#comiis_wx_title_box" )?.innerText; } /* console.log(` 用户名: ${postForumInfo.user} 用户UID: ${postForumInfo.uid} 用户等级: ${postForumInfo.level} 帖子Url: ${postForumInfo.url} 帖子标题: ${postForumInfo.title} 帖子内容(缩略): ${postForumInfo.content} 帖子板块: ${postForumInfo.plate} `); */ for (const shieldItem of shieldUserList) { let shieldOption = shieldItem["option"]; let shieldText = shieldItem["text"]; shieldText = new RegExp(shieldText, "i"); if ( typeof postForumInfo[shieldOption] === "string" && !utils.isNull(postForumInfo[shieldOption]) && postForumInfo[shieldOption].match(shieldText) ) { console.log( `屏蔽 ${shieldOption} ${postForumInfo[shieldOption]}` ); item.remove(); break; } } }); /* 帖子内的每个人的元素列表 */ document .querySelectorAll(".comiis_postlist .comiis_postli") .forEach((item) => { let postForumInfo = { /* 用户名 */ user: item.querySelector("a.top_user").innerText, /* 用户UID */ uid: item .querySelector("a.top_user") .href.match(DOM_CONFIG.urlRegexp.MTUid)[1] .trim(), /* 用户等级 */ level: item .querySelector("a.top_lev") .innerText.replace("Lv.", ""), /* 帖子Url */ url: undefined, /* 帖子标题 */ title: undefined, /* 帖子内容(缩略) */ content: item.querySelector(".comiis_message_table").innerText, /* 帖子板块 */ plate: undefined, }; /* console.log(` 用户名: ${postForumInfo.user} 用户UID: ${postForumInfo.uid} 用户等级: ${postForumInfo.level} 帖子内容: ${postForumInfo.content} `); */ for (const shieldItem of shieldUserList) { let shieldOption = shieldItem["option"]; let shieldText = shieldItem["text"]; shieldText = new RegExp(shieldText, "i"); if ( typeof postForumInfo[shieldOption] === "string" && !utils.isNull(postForumInfo[shieldOption]) && postForumInfo[shieldOption].match(shieldText) ) { console.log( `屏蔽 ${shieldOption} ${postForumInfo[shieldOption]}` ); item.remove(); break; } } }); } if ( window.location.href.match(/bbs.binmt.cc\/home.php\?mod=space&do=pm/) ) { /* 我的消息 */ let shieldUserList = getShieldList(); document .querySelectorAll(".comiis_pms_box .comiis_pmlist ul li") .forEach((item) => { let postForumInfo = { /* 用户名 */ user: item .querySelector("h2") .innerText.replace(item.querySelector("h2 span")?.innerText, "") .replace(/\s*/, ""), /* 用户UID */ uid: item .querySelector("a.b_b") .href.match(DOM_CONFIG.urlRegexp.MTUid)[1] .trim(), /* 用户等级 */ level: undefined, /* 帖子Url */ url: item.querySelector("a.b_b")?.href, /* 帖子标题 */ title: undefined, /* 帖子内容(缩略) */ content: item.querySelector("p.f_c")?.innerText?.trim(), /* 帖子板块 */ plate: undefined, }; /* console.log(` 用户名: ${postForumInfo.user} 用户UID: ${postForumInfo.uid} 帖子内容: ${postForumInfo.content} `); */ for (const shieldItem of shieldUserList) { let shieldOption = shieldItem["option"]; let shieldText = shieldItem["text"]; shieldText = new RegExp(shieldText, "i"); if ( typeof postForumInfo[shieldOption] === "string" && !utils.isNull(postForumInfo[shieldOption]) && postForumInfo[shieldOption].match(shieldText) ) { console.log( `屏蔽 ${shieldOption} ${postForumInfo[shieldOption]}` ); item.remove(); break; } } }); } }, /** * 评论过滤器 * 来源:https://bbs.binmt.cc/thread-122335-1-1.html * 来源:https://greasyfork.org/zh-CN/scripts/479918 */ ownCommentsFilter() { if ( window.location.href.match(DOM_CONFIG.urlRegexp.forumGuideUrl) || window.location.href.match(DOM_CONFIG.urlRegexp.plateUrl) || window.location.href.match(DOM_CONFIG.urlRegexp.forumPost) ) { let ownCommentsFilterData = GM_getValue( "ownCommentsFilterData", DEFAULT_CONFIG.ownCommentsFilterData ); if (!Array.isArray(ownCommentsFilterData["keywords"])) { console.log("评论过滤器:居然不是数组?"); return; } if (!ownCommentsFilterData["keywords"].length) { return; } /** * 判断是否是黑名单用户 */ let isBlackListUser = function (postForumInfo) { for (const userName of ownCommentsFilterData["userBlackList"]) { if ( userName == postForumInfo.user || userName == postForumInfo.uid ) { console.log("评论过滤器:黑名单用户", postForumInfo); return true; } } return false; }; /** * 判断是否是白名单用户 */ let isWhiteListUser = function (postForumInfo) { for (const userName of ownCommentsFilterData["userWhiteList"]) { /* 白名单用户 */ if ( userName === postForumInfo.user || userName === postForumInfo.uid ) { console.log("评论过滤器:白名单用户", postForumInfo); return true; } } return false; }; document .querySelectorAll(".comiis_postlist .comiis_postli") .forEach((item) => { if (item.closest("#comments-is-filter-html")) { /* 不是弹窗里的 */ return; } if (item.querySelector("#comiis_allreplies")) { /* 是主内容 */ return; } let postForumInfo = { /* 用户名 */ user: item.querySelector("a.top_user").innerText || "", /** * 用户UID * @type {string} */ uid: item .querySelector("a.top_user") .href.match(DOM_CONFIG.urlRegexp.MTUid)[1] .trim(), /* 帖子内容(缩略) */ content: item .querySelector(".comiis_message_table") ?.innerText?.trim() || "", isAuthor: Boolean(item.querySelector("span.top_lev")), }; /* 判断是否是白名单用户 */ if (isWhiteListUser(postForumInfo)) { return; } /* 如果是回复评论则去除别人的回复 */ if ( ownCommentsFilterData["replyFlag"] && item.querySelector(".comiis_quote") ) { let comiis_quote_Element = item.querySelector(".comiis_quote"); GLOBAL_DATA.isFilterUserElementList.push( comiis_quote_Element.outerHTML ); comiis_quote_Element.remove(); } if ( postForumInfo.isAuthor && !ownCommentsFilterData["avatarFlag"] ) { /* 当前内容是楼主发的但是不处理楼主 */ return; } /* 判断是否是黑名单用户 */ if (isBlackListUser(postForumInfo)) { GLOBAL_DATA.isFilterUserElementList.push(item.outerHTML); item.remove(); return; } /* 排除小于此长度的评论 */ if ( typeof ownCommentsFilterData["minLength"] === "number" && ownCommentsFilterData["minLength"] > postForumInfo.content.length ) { return; } /* 排除大于此长度的评论 */ if ( typeof ownCommentsFilterData["keywordLength"] === "number" && ownCommentsFilterData["keywordLength"] < postForumInfo.content.length ) { return; } /* 关键字判断 */ for (const keywordItem of ownCommentsFilterData["keywords"]) { if (typeof keywordItem !== "string") { /* ?关键字不是字符串 */ continue; } let keywordPattern = new RegExp(keywordItem); if (postForumInfo.content.match(keywordPattern)) { /* 成功匹配关键字 */ console.log("评论过滤器:", postForumInfo); GLOBAL_DATA.isFilterUserElementList.push(item.outerHTML); item.remove(); return; } } }); } }, /** * 评论区添加点评功能 */ commentsAddReviews() { if ( GM_getValue("v6") && window.location.href.match(DOM_CONFIG.urlRegexp.forumPost) ) { utils.waitNodeList(".bottom_zhan.y").then((nodeList) => { nodeList.forEach((item) => { var bottomZhanNode = item; if (bottomZhanNode.getAttribute("data-isaddreviews")) { return; } bottomZhanNode.setAttribute("data-isaddreviews", true); var replyNode = bottomZhanNode.querySelector("a"); var replyUrl = replyNode.getAttribute("datahref") || replyNode.href; var rewardUrl = replyUrl .replace("mod=post&", "mod=misc&") .replace("action=reply&", "action=comment&"); var reviewPage = replyUrl.match(/&page=([\w]+)/i)[1]; var reviewsUrl = `${rewardUrl}&extra=page%3D1&page=${reviewPage}`; var reviewsPID = bottomZhanNode .closest(".comiis_postli[id]") .getAttribute("id") .replace("pid", "&pid="); reviewsUrl = reviewsUrl + reviewsPID; var reviewsUserName = bottomZhanNode .closest(".comiis_postli[id]") .querySelector(".top_user.f_b").text; var reviewsNode = $jq(` `); reviewsNode.on("click", function () { utils .waitNode("div[id=ntcmsg_popmenu]>div>span.f_c") .then((element) => { try { element.innerText = "点评 " + reviewsUserName; } catch (err) { console.log("修改点评失败", err); } }); }); $jq(bottomZhanNode).prepend(reviewsNode); }); }); } }, /** * 识别链接 * @returns */ identifyLinks() { if (!GM_getValue("v2", false)) { return; } /*TEXT link to Clickable Hyperlink*/ var clearLink, excludedTags, filter, linkMixInit, linkPack, linkify, observePage, observer, setLink, url_regexp, xpath; url_regexp = /((https?:\/\/|www\.)[\x21-\x7e]+[\w\/]|(\w[\w._-]+\.(com|cn|org|net|info|tv|cc))(\/[\x21-\x7e]*[\w\/])?|ed2k:\/\/[\x21-\x7e]+\|\/|thunder:\/\/[\x21-\x7e]+=)/gi; clearLink = function (a) { var b; a = null != (b = a.originalTarget) ? b : a.target; if ( null != a && "a" === a.localName && -1 !== a.className.indexOf("texttolink") && ((b = a.getAttribute("href")), 0 !== b.indexOf("http") && 0 !== b.indexOf("ed2k://") && 0 !== b.indexOf("thunder://")) ) return a.setAttribute("href", "http://" + b); }; document.addEventListener("mouseover", clearLink); setLink = function (a) { /* Uncaught TypeError: a.parentNode.className.indexOf is not a function */ if (typeof a != "object") { return; } /* 看不得报错,增加判断 */ if ( null != a && typeof a.parentNode !== "undefined" && typeof a.parentNode.className !== "undefined" && typeof a.parentNode.className.indexOf === "function" && -1 === a.parentNode.className.indexOf("texttolink") && "#cdata-section" !== a.nodeName ) { var b = a.textContent.replace( url_regexp, '$1' ); if (a.textContent.length !== b.length) { var c = document.createElement("span"); c.innerHTML = b; console.log(`识别: ${c.querySelector("a")}`); return a.parentNode.replaceChild(c, a); } } }; excludedTags = "a svg canvas applet input button area pre embed frame frameset head iframe img option map meta noscript object script style textarea code".split( " " ); xpath = `//text()[not(ancestor::${excludedTags.join( ") and not(ancestor::" )})]`; filter = new RegExp(`^(${excludedTags.join("|")})$`, "i"); linkPack = function (a, b) { var c, d; if (b + 1e4 < a.snapshotLength) { var e = (c = b); for (d = b + 1e4; b <= d ? c <= d : c >= d; e = b <= d ? ++c : --c) setLink(a.snapshotItem(e)); setTimeout(function () { return linkPack(a, b + 1e4); }, 15); } else for ( e = c = b, d = a.snapshotLength; b <= d ? c <= d : c >= d; e = b <= d ? ++c : --c ) setLink(a.snapshotItem(e)); }; linkify = function (a) { a = document.evaluate( xpath, a, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null ); return linkPack(a, 0); }; observePage = function (a) { for ( a = document.createTreeWalker( a, NodeFilter.SHOW_TEXT, { acceptNode: function (a) { if (!filter.test(a.parentNode.localName)) return NodeFilter.FILTER_ACCEPT; }, }, !1 ); a.nextNode(); ) setLink(a.currentNode); }; observer = new window.MutationObserver(function (a) { var b, c; var d = 0; for (b = a.length; d < b; d++) { var e = a[d]; if ("childList" === e.type) { var g = e.addedNodes; var f = 0; for (c = g.length; f < c; f++) (e = g[f]), observePage(e); } } }); linkMixInit = function () { /* if (window === window.top && "" !== window.document.title) return linkify(document.body), observer.observe(document.body, { childList: !0, subtree: !0 }) 修改为可在iframe内执行 */ return ( linkify(document.body), observer.observe(document.body, { childList: !0, subtree: !0, }) ); }; var clearlinkF = function (a) { var url = a.getAttribute("href"); if ( 0 !== url.indexOf("http") && 0 !== url.indexOf("ed2k://") && 0 !== url.indexOf("thunder://") ) return a.setAttribute("href", "http://" + url); }, clearlinkE = function () { for ( var a = document.getElementsByClassName("texttolink"), b = 0; b < a.length; b++ ) clearlinkF(a[b]); }; setTimeout(clearlinkE, 1500); setTimeout(linkMixInit, 100); }, /** * 显示用户的uid */ showUserUID() { if ( GM_getValue("v15") && (window.location.href.match(DOM_CONFIG.urlRegexp.forumPostGuideUrl) || window.location.href.match(DOM_CONFIG.urlRegexp.forumPost) || window.location.href.match(DOM_CONFIG.urlRegexp.plateUrl) || window.location.href.match(DOM_CONFIG.urlRegexp.searchUrl) || window.location.href.match( /bbs.binmt.cc\/home.php\?mod=space&do=thread&view=me/ ) || window.location.href.match( /home.php\?mod=space&uid=.+&do=thread&view=me/ )) ) { if (!window.GM_isaddShowUidCss) { window.GM_isaddShowUidCss = true; GM_addStyle(` .postli_top_tximg + h2{ height: auto; } `); } let forumList = null; let isFind = false; /* 是否找到帖子 */ let isFinding = false; /* 是否正在找到帖子 */ utils.mutationObserver(document.documentElement, { callback: (mutations, observer) => { /* 判断是否已找到 */ if (isFind) { handleShowUserUID(); /* console.log("成功找到帖子DOM"); */ observer.disconnect(); return; } /* 正在寻找中 */ if (isFinding) { return; } isFinding = true; forumList = utils.getNodeListValue( DOM_CONFIG.element.comiisForumList, DOM_CONFIG.element.comiisPostli, DOM_CONFIG.element.comiisMmlist ); isFind = forumList.length ? true : false; !isFind && (forumList = null); setTimeout(() => { isFinding = false; }, 250); }, config: { subtree: true, childList: true }, }); /** * 处理显示用户UID */ const handleShowUserUID = function () { GM_addStyle(` .comiis_postli_top.bg_f.b_t h2{ height: auto; }`); function matchUIDByArray(data) { for (let i = 0; i < data.length; i++) { let url = data[i].href; let uid = url.match(DOM_CONFIG.urlRegexp.MTUid); if (uid) { return uid[1]; } } return null; } $jq.each(forumList, (index, value) => { let mtUIDOM = value.getElementsByClassName("mt_uid_set"); if (!mtUIDOM.length) { let childrenByATagetElement = value.getElementsByTagName("a"); let mt_uid = null; mt_uid = matchUIDByArray(childrenByATagetElement); if (mt_uid != null) { let uid_control = document.createElement("a"); let mtUidDomInsertElement = value.getElementsByClassName("top_lev")[0]; let uid_control_height = getComputedStyle( mtUidDomInsertElement, null )["height"]; let uid_control_margin = getComputedStyle( mtUidDomInsertElement, null )["margin"]; let uid_control_padding = getComputedStyle( mtUidDomInsertElement, null )["padding"]; let uid_control_line_height = getComputedStyle( mtUidDomInsertElement, null )["line-height"]; let uid_control_font = getComputedStyle( mtUidDomInsertElement, null )["font"]; let uid_control_bg_color = "#FF7600"; uid_control.className = "mt_uid_set"; uid_control.style = ` font: ${uid_control_font}; background: ${uid_control_bg_color}; color: white; float: left; margin: ${uid_control_margin}; padding: ${uid_control_padding}; height: ${uid_control_height}; line-height: ${uid_control_line_height}; border-radius: 1.5px;`; uid_control.innerHTML = "UID:" + mt_uid; uid_control.onclick = function () { try { GM_setClipboard(mt_uid); popups.toast(`${mt_uid}已复制`); console.log("复制:", mt_uid); } catch (err) { popups.toast(`${mt_uid}复制失败`); console.log("复制失败:" + mt_uid, err); } }; mtUidDomInsertElement.parentElement.append(uid_control); } } }); }; } }, /** * 显示用户的标签,比如UID或自定义的 */ showUserLabels() { let customizeUserLabelsList = GM_getValue("customizeUserLabelsList", []); if (!customizeUserLabelsList.length) { console.log("未设置用户自定义标签"); return; } if ( window.location.href.match(DOM_CONFIG.urlRegexp.forumPostGuideUrl) || window.location.href.match(DOM_CONFIG.urlRegexp.forumPost) || window.location.href.match(DOM_CONFIG.urlRegexp.plateUrl) || window.location.href.match(DOM_CONFIG.urlRegexp.searchUrl) || window.location.href.match( /bbs.binmt.cc\/home.php\?mod=space&do=thread&view=me/ ) || window.location.href.match( /home.php\?mod=space&uid=.+&do=thread&view=me/ ) ) { /** * 处理显示用户自定义标签 */ const handleShowUserLabels = { forumList: null, isSetCSS: false, /** * 是否找到帖子 */ isFind: false, /** * 是否正在找到帖子 */ isFinding: false, /** * 设置样式 */ setCSS() { if (this.isSetCSS) { return; } GM_addStyle(` .comiis_postli_top.bg_f.b_t h2{ height: auto; }`); GM_addStyle(` .postli_top_tximg + h2{ height: auto; } `); }, /** * 根据超链接元素获取UID * @param {Element} ele * @returns */ matchUIDByArray(ele) { for (let i = 0; i < ele.length; i++) { let url = ele[i].href; let uid = url.match(DOM_CONFIG.urlRegexp.MTUid); if (uid) { return uid[1]; } } return null; }, handleForum() { $jq.each(handleShowUserLabels.forumList, (index, value) => { let user_label_ele = value.querySelector( "a.mt_custom_user_labels" ); if (user_label_ele) { return; } let hyperLinkElement = value.getElementsByTagName("a"); let MT_UID = null; MT_UID = handleShowUserLabels.matchUIDByArray(hyperLinkElement); if (utils.isNull(MT_UID)) { return; } MT_UID = parseInt(MT_UID); let findUserLabelsList = []; customizeUserLabelsList.forEach((item) => { if (MT_UID === item["uid"]) { findUserLabelsList = [...findUserLabelsList, item]; } }); if (!findUserLabelsList.length) { return; } let mtUidDomInsertElement = value.getElementsByClassName("top_lev")[0]; let uid_control_height = getComputedStyle( mtUidDomInsertElement, null )["height"]; let uid_control_margin = getComputedStyle( mtUidDomInsertElement, null )["margin"]; let uid_control_padding = getComputedStyle( mtUidDomInsertElement, null )["padding"]; let uid_control_line_height = getComputedStyle( mtUidDomInsertElement, null )["line-height"]; let uid_control_font = getComputedStyle( mtUidDomInsertElement, null )["font"]; findUserLabelsList.forEach((item) => { let labelElement = document.createElement("a"); let labelBgColor = item["color"]; labelElement.className = "mt_custom_user_labels"; labelElement.style = ` font: ${uid_control_font}; background: ${labelBgColor}; color: white; float: left; margin: ${uid_control_margin}; padding: ${uid_control_padding}; height: ${uid_control_height}; line-height: ${uid_control_line_height}; border-radius: 1.5px; ${item["style"]}`; labelElement.innerHTML = item["labels"]; if (utils.isNotNull(item["js"])) { labelElement.onclick = function () { let that = this; utils .tryCatch() .error(function (error) { popups.confirm({ title: "执行JS失败", text: `

    ${error.toString()}

    `, }); }) .run(item["js"], that); }; } mtUidDomInsertElement.parentElement.append(labelElement); }); }); }, run() { let that = this; this.setCSS(); utils.mutationObserver(document.documentElement, { callback: (mutations, observer) => { /* 判断是否已找到 */ if (that.isFind) { that.handleForum(); /* console.log("成功找到帖子DOM"); */ observer.disconnect(); return; } /* 正在寻找中 */ if (that.isFinding) { return; } that.isFinding = true; that.forumList = utils.getNodeListValue( DOM_CONFIG.element.comiisForumList, DOM_CONFIG.element.comiisPostli, DOM_CONFIG.element.comiisMmlist ); that.isFind = Boolean(that.forumList.length); !that.isFind && (that.forumList = null); setTimeout(() => { that.isFinding = false; }, 250); }, config: { subtree: true, childList: true }, }); }, }; handleShowUserLabels.run(); } }, /** * 页面小窗浏览帖子 */ pageSmallWindowBrowsingForumPost() { if ( !GM_getValue("v45", false) && (!window.location.href.match(DOM_CONFIG.urlRegexp.forumGuideUrl) || !window.location.href.match(DOM_CONFIG.urlRegexp.searchUrl) || !window.location.href.match(DOM_CONFIG.urlRegexp.homeUrlBrief)) ) { return; } let small_icon_width = 24; let small_right_btn_width = 115; let small_title_width = `calc(100% - ${ small_icon_width + small_right_btn_width }px)`; function initCSS() { GM_addStyle(` .xtiper_sheet,.xtiper_sheet .xtiper_sheet_tit{border-radius:18px 18px 0 0} .xtiper_sheet_tit.xtiper_sheet_left{display:block;background:#fff;width:100%;box-sizing:border-box} .xtiper_sheet_tit.xtiper_sheet_left img.xtiper_tit_ico{background: #fff;filter: invert(100%);width: ${small_icon_width}px;height: ${small_icon_width}px;align-self: center;border-radius: 3px} .xtiper_sheet_tit.xtiper_sheet_left .xtiper_tit_content{margin-left: 22px;width: ${small_title_width}} .xtiper_sheet_tit.xtiper_sheet_left .xtiper_tit_content p{word-wrap:break-word;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} .xtiper_sheet_tit.xtiper_sheet_left .xtiper_tit_content .xtiper_tit_svg_lock{display:flex;align-items:center} .xtiper_sheet_tit.xtiper_sheet_left .xtiper_tit_content .xtiper_tit_svg_lock svg{margin:0 6px 0 2px} .xtiper_sheet_tit.xtiper_sheet_left .xtiper_tit_right { display: inline-flex; align-items: center; align-content: center; width: ${small_right_btn_width}px; justify-content: center; } .xtiper_sheet_tit.xtiper_sheet_left .xtiper_tit_right_picture,.xtiper_sheet_tit.xtiper_sheet_left .xtiper_tit_right_windowclose,.xtiper_sheet_tit.xtiper_sheet_left .xtiper_tit_right_windowopen{width:100%;text-align:center;margin:0 0;height:100%;display:flex;justify-content:center;align-items:center} .xtiper_content.xtit{height:calc(100% - 80px)!important} .xtiper.xtiper_msg.xtiper_msg_bottom.xtiper_msg_black.xon{margin-bottom:30px} .xtiper_sheet_tit_top_drag{width:100%;position:relative;height:10px} .xtiper_sheet_tit_top_drag div{width:50px;margin:0 auto;height:4px;background:#d9d9d9;border-radius:15px;bottom:3px;position:relative} `); GM_addStyle(` .refresh-icon{width:40px;display:flex;align-items:center} .refresh-icon-in,.refresh-icon-out{position:absolute;border:5px solid rgba(0,183,229,.9);opacity:.9;border-radius:50px;box-shadow:0 0 15px #2187e7;width:20px;height:20px;margin:0 auto} .refresh-icon-out{background-color:rgba(0,0,0,0);border-right:5px solid transparent;border-left:5px solid transparent;-moz-animation:spinPulse 1s infinite ease-in-out;-webkit-animation:spinPulse 1s infinite ease-in-out;-o-animation:spinPulse 1s infinite ease-in-out;-ms-animation:spinPulse 1s infinite ease-in-out} .refresh-icon-in{background:rgba(0,0,0,0) no-repeat center center;border-top:5px solid transparent;border-bottom:5px solid transparent;-moz-animation:spinoffPulse 3s infinite linear;-webkit-animation:spinoffPulse 3s infinite linear;-o-animation:spinoffPulse 3s infinite linear;-ms-animation:spinoffPulse 3s infinite linear} @-moz-keyframes spinPulse{0%{-moz-transform:rotate(160deg);opacity:0;box-shadow:0 0 1px #505050} 50%{-moz-transform:rotate(145deg);opacity:1} 100%{-moz-transform:rotate(-320deg);opacity:0} } @-moz-keyframes spinoffPulse{0%{-moz-transform:rotate(0)} 100%{-moz-transform:rotate(360deg)} } @-webkit-keyframes spinPulse{0%{-webkit-transform:rotate(160deg);opacity:0;box-shadow:0 0 1px #505050} 50%{-webkit-transform:rotate(145deg);opacity:1} 100%{-webkit-transform:rotate(-320deg);opacity:0} } @-webkit-keyframes spinoffPulse{0%{-webkit-transform:rotate(0)} 100%{-webkit-transform:rotate(360deg)} } @-o-keyframes spinPulse{0%{-o-transform:rotate(160deg);opacity:0;box-shadow:0 0 1px #505050} 50%{-o-transform:rotate(145deg);opacity:1} 100%{-o-transform:rotate(-320deg);opacity:0} } @-o-keyframes spinoffPulse{0%{-o-transform:rotate(0)} 100%{-o-transform:rotate(360deg)} } @-ms-keyframes spinPulse{0%{-ms-transform:rotate(160deg);opacity:0;box-shadow:0 0 1px #505050} 50%{-ms-transform:rotate(145deg);opacity:1} 100%{-ms-transform:rotate(-320deg);opacity:0} } @-ms-keyframes spinoffPulse{0%{-ms-transform:rotate(0)} 100%{-ms-transform:rotate(360deg)} } @-moz-keyframes spinPulse{0%{-moz-transform:rotate(160deg);opacity:0;box-shadow:0 0 1px #505050} 50%{-moz-transform:rotate(145deg);opacity:1} 100%{-moz-transform:rotate(-320deg);opacity:0} } @-moz-keyframes spinoffPulse{0%{-moz-transform:rotate(0)} 100%{-moz-transform:rotate(360deg)} } @-webkit-keyframes spinPulse{0%{-webkit-transform:rotate(160deg);opacity:0;box-shadow:0 0 1px #505050} 50%{-webkit-transform:rotate(145deg);opacity:1} 100%{-webkit-transform:rotate(-320deg);opacity:0} } @-webkit-keyframes spinoffPulse{0%{-webkit-transform:rotate(0)} 100%{-webkit-transform:rotate(360deg)} } @-o-keyframes spinPulse{0%{-o-transform:rotate(160deg);opacity:0;box-shadow:0 0 1px #505050} 50%{-o-transform:rotate(145deg);opacity:1} 100%{-o-transform:rotate(-320deg);opacity:0} } @-o-keyframes spinoffPulse{0%{-o-transform:rotate(0)} 100%{-o-transform:rotate(360deg)} } @-ms-keyframes spinPulse{0%{-ms-transform:rotate(160deg);opacity:0;box-shadow:0 0 1px #505050} 50%{-ms-transform:rotate(145deg);opacity:1} 100%{-ms-transform:rotate(-320deg);opacity:0} } @-ms-keyframes spinoffPulse{0%{-ms-transform:rotate(0)} 100%{-ms-transform:rotate(360deg)} }`); } /** * 获取当前页面所有帖子 * @returns */ function getForumList() { return utils.getNodeListValue( DOM_CONFIG.element.comiisForumList, DOM_CONFIG.element.comiisPostli, DOM_CONFIG.element.comiisMmlist ); } function setUrlHash() { oldUrl = window.location.href; let smallWindowHashUrl = oldUrl + smallWindowHash; window.history.pushState({}, null, smallWindowHashUrl); console.log("设置小窗hash Url:" + smallWindowHashUrl); window.history.forward(1); } /** * 设置浏览器历史地址 */ function popStateEvent() { setUrlHash(); resumeBack(); } /** * 禁止浏览器后退按钮 */ function banBack() { if (window.history && window.history.pushState) { $jq(window).on("popstate", popStateEvent); } /* 在IE中必须得有这两行 */ setUrlHash(); } /** * 允许浏览器后退并关闭小窗 * @returns */ async function resumeBack() { xtip.close(smallWindowId); smallWindowId = null; $jq(window).off("popstate", popStateEvent); while (1) { if (window.location.hash.startsWith(smallWindowHash)) { console.log("back!"); window.history.back(); await utils.sleep(100); } else { return; } } } function showSmallWindow(title, url, imagesList = []) { /* 显示小窗 */ let constructURL = new URL(url); let isHTTPS = constructURL.protocol.includes("https:"); let icon_safe = ` `; /* 安全的图标 */ let icon_unsafe = ` `; /* 不安全的图标 */ let icon_openBlank = ` `; /* 新标签页打开的按钮 */ let icon_close = ` `; /* 关闭的按钮 */ let icon_picture_html = imagesList.length !== 0 ? `
    ` : ""; /* 图片按钮 */ let showWebsiteSafeIcon = isHTTPS ? icon_safe : icon_unsafe; let websiteTitle = `

    ${title}

    ${showWebsiteSafeIcon}

    ${constructURL.host}

    ${icon_picture_html}
    ${icon_openBlank}
    ${icon_close}
    `; let smallWindowIframeId = xtip.open({ type: "url", content: url, title: websiteTitle, height: "92%", app: true, success: () => { banBack(); }, end: () => { console.log("点击其它区域关闭小窗"); resumeBack(); }, }); smallWindowId = smallWindowIframeId; console.log(smallWindowId); let dragNode = new AnyTouch( document.getElementById(smallWindowIframeId) ); let smallWidowNode = document .getElementById(smallWindowIframeId) .querySelector("div.xtiper_sheet"); let smallWidowNormalHeight = parseInt( smallWidowNode.style["height"] ); /* 小窗原始高度 */ console.log("小窗原始高度", smallWidowNormalHeight); dragNode.on("pan", (event) => { if (event.phase == "move" && event.displacementY > 0) { /* 当前为向下移动 */ smallWidowNode.style["transition"] = "none"; smallWidowNode.style["height"] = Math.abs(smallWidowNormalHeight - event.distanceY) + "px"; } if (event.isEnd) { /* 当前为停止移动,松开手指,判断在哪个区域,一半以上回归上面,一般以下,关闭 */ smallWidowNode.style["transition"] = "0.2s ease-in"; if ( parseInt(smallWidowNode.style["height"]) > window.innerHeight / 2 ) { smallWidowNode.style["height"] = smallWidowNormalHeight + "px"; } else { resumeBack(); } } }); dragNode.on("tap", (event) => { if ( document .getElementById(smallWindowIframeId) .querySelector(".xtiper_bg") .outerHTML.includes(event.target.outerHTML) ) { /* 点击背景关闭小窗 */ console.log("点击背景关闭小窗"); resumeBack(); dragNode.off("tap"); dragNode.off("pan"); return; } if ( document .getElementById(smallWindowIframeId) .querySelector(".xtiper_tit_content") .outerHTML.includes(event.target.outerHTML) ) { if (title !== "") { GM_setClipboard(`『${title}』 - ${url}`); } else { GM_setClipboard(url); } xtips.toast("已复制链接", { icon: "success", pos: "bottom", }); return; } if ( document .querySelector("#" + smallWindowId) .querySelector(".xtiper_tit_right_picture") && document .querySelector("#" + smallWindowId) .querySelector(".xtiper_tit_right_picture i") .outerHTML.includes(event.target.outerHTML) ) { /* 点击查看图片 */ console.log("点击查看图片", imagesList); var viewerULNodeHTML = ""; imagesList.forEach((item) => { viewerULNodeHTML += `
  • `; }); var viewerULNode = $jq(`
      ${viewerULNodeHTML}
    `)[0]; let viewer = new Viewer(viewerULNode, { inline: false, url: "data-src", zIndex: utils.getMaxZIndex() + 100, hidden: () => { viewer.destroy(); }, }); viewer.zoomTo(1); viewer.show(); } if ( document .getElementById(smallWindowIframeId) .querySelector(".xtiper_tit_right_windowopen svg") .outerHTML.includes(event.target.outerHTML) ) { /* 点击 新标签页打开 */ window.open(url, "_blank"); return; } if ( document .getElementById(smallWindowIframeId) .querySelector(".xtiper_tit_right_windowclose svg") .outerHTML.includes(event.target.outerHTML) ) { /* 点击 关闭小窗 */ console.log("点击 关闭小窗"); resumeBack(); dragNode.off("tap"); dragNode.off("pan"); return; } if ( document .querySelector(".xtiper_tit_ico") .outerHTML.includes(event.target.outerHTML) || document .querySelector(".xtiper_sheet .refresh-icon") .outerHTML.includes(event.target.outerHTML) ) { /* 点击 刷新iframe */ console.log("点击 刷新iframe"); mobileBusiness.smallWindow.setRefreshIconShow(); document .querySelector("#" + smallWindowIframeId) ?.querySelector("iframe") ?.contentWindow?.location?.reload(); } }); mobileBusiness.smallWindow.checkIframeReadyState(); } /** * 对帖子进行处理,实现点击某个区域打开小窗 * @param {NodeListOf { imagesList = [...imagesList, ImgNode.getAttribute("src")]; }); value.find(".comiis_pyqlist_imgs img").each((imgIndex, ImgNode) => { imagesList = [...imagesList, ImgNode.getAttribute("src")]; }); value.find(".mmlist_li_box a").each((aIndex, aNode) => { aNode.removeAttribute("href"); aNode.setAttribute("data-href", url); }); value.find(".mmlist_li_box").on("click", function (event) { var mouseClickPosX = Number( window.event.clientX ); /* 鼠标相对屏幕横坐标 */ if (document.body.offsetWidth / 2 > mouseClickPosX) { window.location.href = url; } else { showSmallWindow(title, url, imagesList); } }); }); } let isHandling = false; let smallWindowId = null; /* 小窗对象 */ let smallWindowHash = "#/smallWindow"; let oldUrl = window.location.href; utils.mutationObserver(document.documentElement, { callback: (mutations, observer) => { /* 正在寻找中 */ if (isHandling) { return; } isHandling = true; let forumlist = getForumList(); if (forumlist.length) { initCSS(); handleForumPost(forumlist); isHandling = false; observer.disconnect(); return; } setTimeout(() => { isHandling = false; }, 250); }, config: { subtree: true, childList: true }, }); }, /** * 代码块优化 */ codeQuoteOptimization() { if ( !GM_getValue("v46") && !window.location.href.match(DOM_CONFIG.urlRegexp.forumPost) ) { return; } if (!DOM_CONFIG.isSetHljsCSS) { DOM_CONFIG.isSetHljsCSS = true; $jq(document.head).append( $jq( `` ) ); hljs.registerLanguage("smali", CommonFunc.hljs_smali); GM_addStyle(` .hljs ol{margin:0 0 0 10px;padding:10px 10px 10px 25px} .hljs li{padding-left:10px;list-style-type:decimal-leading-zero;font-family:Monaco,Consolas,'Lucida Console','Courier New',serif;font-size:12px;line-height:1.8em} .hljs li:hover{background:#2c313c} .hljs li::marker{unicode-bidi:isolate;font-variant-numeric:tabular-nums;text-transform:none;text-indent:0!important;text-align:start!important;text-align-last:start!important} select.code-select-language{height:40px;line-height:40px;font-size:14px;border:1px solid #5c5c5c;border-radius:5px;text-align:center;outline:0;margin-left:10px} `); GM_addStyle(` .reader-copy-button{background:#000;background-size:cover;background-repeat:no-repeat;background-position:0;color:#fff;line-height:40px;display:block;text-align:center;border-radius:5px;cursor:pointer;font-size:15px;width:70px;user-select:none} .reader-copy-button i{display:inline-block;margin-right:6px;width:16px;height:16px;background-size:cover;vertical-align:sub;user-select:none} `); $jq(document).on("click", ".reader-copy-button", function (event) { utils.preventEvent(event); let codeElement = document.querySelector( event.target.getAttribute("data-code-selector") ); console.log("点击复制"); GM_setClipboard(codeElement.outerText || codeElement.innerText); popups.toast("已复制到剪贴板"); return false; }); } let comiis_blockcode = $jq(".comiis_blockcode.comiis_bodybg"); $jq.each(comiis_blockcode, (index, value) => { if (value.getAttribute("data-copy")) { return; } value.setAttribute("data-copy", true); let tempDivElement = $jq(`
    复制按钮 复制
    `); $jq(value).before(tempDivElement); /** * 设置元素高亮 * @param {HTMLElement} ele * @param {string} language 语言,默认为Java */ function setElementHighlight(ele, language = "java") { if (!ele.oldValue) { ele.oldValue = ele.textContent; } ele.innerHTML = hljs .highlight(ele.oldValue, { language: language }) .value.replace(/\\n$/gi, ""); } /* 获取当前代码块的文本内容 */ let codeLanguage = hljs.highlightAuto(value.textContent).language; let selectElementParentDiv = document.createElement("div"); let selectElement = document.createElement("select"); let selectLanguageList = hljs.listLanguages().sort(); selectLanguageList = selectLanguageList.concat("自动检测"); let selectInnerHTML = ""; selectLanguageList.forEach((languageName) => { if (languageName.startsWith("自动检测")) { selectInnerHTML += ``; } else { selectInnerHTML += ``; } }); selectElement.className = "code-select-language"; selectElement.innerHTML = selectInnerHTML; $jq(selectElement).on("change", function () { let changeCodeLanguage = this.selectedOptions[0].getAttribute("data-value"); selectElement.setAttribute("aria-label", changeCodeLanguage); console.log("切换代码块语言: ", changeCodeLanguage); value.querySelectorAll("li").forEach((liElement) => { setElementHighlight(liElement, changeCodeLanguage); }); }); utils.preventEvent(selectElement, "click"); selectElementParentDiv.appendChild(selectElement); tempDivElement.append(selectElementParentDiv); utils.dispatchEvent(selectElement, "change"); value.className = "hljs"; value.firstChild.removeAttribute("class"); tempDivElement .find(".reader-copy-button") .attr("data-code-selector", utils.getElementSelector(value)); }); }, /** * 取消绑定回复底部回复按钮的默认事件 */ editorOptimizationOffDefaultBottomReplyBtnClickEvent() { if (!GM_getValue("v49", false)) { return; } $jq.each( $jq(".comiis_postli_times .dialog[href*=reply]"), (index, item) => { /* 把回复按钮的href改成JavaScript:; */ let href = item.getAttribute("href"); if (href != "javascript:;") { item.setAttribute("class", "f_c dialog_reply"); item.setAttribute("datahref", href); item.setAttribute("href", "javascript:;"); } } ); }, /** * 移除评论区字体效果 */ removeForumPostCommentFontStyle() { if ( GM_getValue("v3") && window.location.href.match(DOM_CONFIG.urlRegexp.forumPost) ) { var fontNodeList = document.querySelectorAll("font"); /* 帖子主内容 */ var postForumMain = document.querySelector(".comiis_postlist.kqide .comiis_postli") ?.innerHTML || ""; if (postForumMain !== "") { for (let i = 0; i < fontNodeList.length; i++) { /* font元素是帖子主内容的移除字体效果 */ if (!postForumMain.includes(fontNodeList[i].innerHTML)) { /* console.log(hide[i].innerHTML); */ fontNodeList[i].removeAttribute("color"); fontNodeList[i].removeAttribute("style"); fontNodeList[i].removeAttribute("size"); } } } /* 帖子评论 */ var postForumComment = document.querySelectorAll( ".comiis_message.bg_f.view_all.cl.message" ); for (let i = 0; i < postForumComment.length; i++) { if (!postForumMain.includes(postForumComment[i].innerHTML)) { postForumComment[i].innerHTML = postForumComment[ i ].innerHTML.replace(DOM_CONFIG.urlRegexp.fontSpecial, ""); if (postForumComment[i].nextElementSibling.localName === "strike") { console.log("影响后面出现下划线的罪魁祸首", postForumComment[i]); postForumComment[i].nextElementSibling.outerHTML = postForumComment[i].nextElementSibling.outerHTML .replace(/^(\n|)/g, "") .replace(/<\/strike>$/g, ""); } } } /* 所有评论,包括帖子主体 */ document .querySelectorAll(".comiis_postli.comiis_list_readimgs.nfqsqi") .forEach((item) => { if (item.parentElement.localName === "strike") { try { item.parentElement.outerHTML = item.parentElement.outerHTML .replace(/^(\n|)/g, "") .replace(/<\/strike>$/g, ""); } catch (error) {} } }); } }, /** * 贴内图片查看优化 * @returns */ imageViewingOptimizationInThePost() { if ( !GM_getValue("v55", false) || !window.location.href.match(DOM_CONFIG.urlRegexp.forumPost) ) { return; } function viewIMG(imgList = [], index = 0) { /* 查看图片 */ let viewerULNodeHTML = ""; imgList.forEach((item) => { viewerULNodeHTML += `
  • `; }); let viewerULNode = $jq(`
      ${viewerULNodeHTML}
    `)[0]; let viewer = new Viewer(viewerULNode, { inline: false, url: "data-src", zIndex: utils.getMaxZIndex() + 100, hidden: () => { viewer.destroy(); }, }); console.log("查看的图片的下标", index); viewer.view(index); viewer.zoomTo(1); viewer.show(); } utils .waitNodeList("div.comiis_postlist.kqide .comiis_postli") .then((nodeList) => { nodeList.forEach((item) => { if (item.getAttribute("isHandlingViewIMG")) { /* 已处理过 */ return; } let clickShowIMGList = []; /* 点击显示的图片组 */ item.querySelectorAll("img").forEach((_item_) => { let IMG_URL = _item_.src; /* 图片链接 */ let IMG_URL_HOSTNAME = new URL(IMG_URL).hostname; /* 主机名 */ let IMG_URL_PATHNAME = new URL(IMG_URL).pathname; /* 路径 */ let imgParentNode = _item_.parentElement; /* img标签的父元素 */ if (imgParentNode.nodeName.toLowerCase() === "span") { imgParentNode.removeAttribute("onclick"); } if ( imgParentNode.nodeName.toLowerCase() === "a" && imgParentNode.getAttribute("href") === IMG_URL ) { imgParentNode.setAttribute("href", "javascript:;"); imgParentNode.removeAttribute("target"); } let isMatching = false; for (let item of DOM_CONFIG.blackListNoViewIMG) { /* 图片黑名单 */ if ( IMG_URL_HOSTNAME.indexOf(item["hostName"]) != -1 && IMG_URL_PATHNAME.match(item["pathName"]) ) { isMatching = true; break; } } if (isMatching) { return; } clickShowIMGList = [...clickShowIMGList, IMG_URL]; $jq(_item_).on("click", function () { console.log("点击图片", _item_); let _index_ = clickShowIMGList.findIndex((_img_) => { return _img_ == IMG_URL; }); viewIMG(clickShowIMGList, _index_); }); }); if (clickShowIMGList.length) { console.log(item); console.log("处理的图片", clickShowIMGList); } item.setAttribute("isHandlingViewIMG", true); }); }); }, }; /** * 移动端单独的函数调用 */ const mobileBusiness = { smallWindow: { /** * 设置小窗标题左边刷新图标(显示)并隐藏网站图标 */ setRefreshIconShow() { document .querySelector(".xtiper_sheet .xtiper_tit_ico") .style.setProperty("display", "none"); document .querySelector(".xtiper_sheet .refresh-icon") .removeAttribute("style"); }, /** * 设置小窗标题左边刷新图标(隐藏)并显示网站图标 */ setRefreshIconHide() { document .querySelector(".xtiper_sheet .refresh-icon") .style.setProperty("display", "none"); document .querySelector(".xtiper_sheet .xtiper_tit_ico") .removeAttribute("style"); }, /** * 设置消息监听 */ setMessageListener() { console.log("监听message"); window.addEventListener("message", (event) => { if (!event.data.toString().startsWith("xtip")) { return; } if (event.data === "xtip complete") { console.log("小窗内容已加载完毕2"); this.setRefreshIconHide(); } else { console.log("小窗内容加载中"); this.setRefreshIconShow(); } }); if (window !== top.window) { window.parent.postMessage("xtip complete"); } }, /** * 检查iframe内文档状态 */ checkIframeReadyState() { let iframeElement = document.querySelector( ".xtiper_sheet iframe" ).contentWindow; let intervalId = setInterval(() => { if ( iframeElement.document && iframeElement.document.readyState === "complete" ) { console.log("小窗内容已加载完毕1"); this.setRefreshIconHide(); clearInterval(intervalId); } }, 400); }, }, }; /** * 手机端执行的函数 */ const mobile = { /** * 主运行方法 */ main() { /* 手机版按顺序加载的函数 */ /* 禁止自动执行的函数(这些函数在其它地方调用) */ const notRunFunc = [ "main", "registerSettingView", "editorChartBed", "previewPostForum", "selectPostingSection", ]; Object.keys(mobile).forEach((key) => { if ( typeof mobile[key] !== "function" || notRunFunc.indexOf(key) != -1 ) { return; } if (key === "loadNextComments") { utils .tryCatch() .error(() => { $jq("#loading-comment-tip").text("加载评论失败"); }) .run(mobile.loadNextComments, this); return; } if (key === "loadPrevComments") { utils .tryCatch() .error(() => { $jq("#loading-comment-tip-prev").text("加载评论失败"); }) .run(mobile.loadPrevComments, this); return; } utils.tryCatch().run(mobile[key], this); mobileRepeatFunc.main(); }); unsafeWindow.popups = popups; popups.init(); }, /** * 自动展开帖子内容 */ autoExpendFullTextByForumPost() { if ( GM_getValue("v18") && location.href.match(DOM_CONFIG.urlRegexp.forumPost) ) { GM_addStyle(` div.comiis_message.bg_f.view_one.b_b.cl.message>div.comiis_messages.comiis_aimg_show.cl{max-height:inherit!important;overflow-y:inherit!important;position:inherit!important} .comiis_lookfulltext_bg,.comiis_lookfulltext_key{display:none!important} `); } }, /** * 每请求一页,自动签到 * @returns {Promise} */ async autoSignIn() { /** * 检测是否登录 * @returns {Promise} */ async function checkLogin() { /* 最后访问Cookie */ let mobile_lastvisit_cookie = await getCookie("cQWy_2132_lastvisit"); console.log( "账号cQWy_2132_lastvisit: ", mobile_lastvisit_cookie ? utils.formatTime(parseInt(mobile_lastvisit_cookie) * 1000) : mobile_login_cookie ); if (envIsMobile()) { /* 移动端的退出按钮,不登录是不会出现的 */ let mobile_login_exitBtn = document.querySelector( ".sidenv_exit a[href*='member.php?mod=logging&action=logout']" ); /* 登录Cookie,通过移动端登录,该Cookie不会HttpOnly,但是通过桌面端和调用QQ登录会 */ let mobile_login_cookie = await getCookie("cQWy_2132_auth"); mobile_login_cookie && (mobile_login_cookie = mobile_login_cookie.slice(0, 8) + "..."); console.log("移动端登录: ", mobile_login_exitBtn); console.log("账号cQWy_2132_auth: ", mobile_login_cookie); return mobile_login_exitBtn || mobile_login_cookie; } else { /* 桌面端登录 */ let pc_login = document.querySelector("#comiis_key"); console.log("桌面端登录: ", pc_login); return pc_login; } } /** * 获取Cookie,使用了GM_cookie,可能在某些油猴管理器上不兼容 * @param {string} cookieName 需要获取的Cookie名字 * @async */ function getCookie(cookieName) { return new Promise((resolve) => { WhiteSev_GM_Cookie.list( { name: cookieName }, function (cookies, error) { if (error) { resolve(null); } else { if (cookies.length == 0) { resolve(null); } else { resolve(cookies[0].value); } } } ); }); } /** * 获取账号的formhash * @returns {string} */ function getFormHash() { let inputFormHash = top.document.querySelector("input[name=formhash]"); let sidenv_exit = top.document.querySelector( "div[class=sidenv_exit]>a" ); /* 退出按钮(登录状态才有),电脑版的 */ let sidenv_exit_match = null; let comiis_recommend_addkey = top.document.querySelector( "a.comiis_recommend_addkey" ); /* 论坛浏览图片下的点赞按钮,获取formhash */ let comiis_recommend_addkey_match = null; inputFormHash = inputFormHash ? inputFormHash.value : null; if (sidenv_exit) { sidenv_exit_match = sidenv_exit.href.match( DOM_CONFIG.urlRegexp.formhash ); sidenv_exit_match = sidenv_exit_match ? sidenv_exit_match[sidenv_exit_match.length - 1] : null; } if (comiis_recommend_addkey) { comiis_recommend_addkey_match = comiis_recommend_addkey.href.match( DOM_CONFIG.urlRegexp.hash ); comiis_recommend_addkey_match = comiis_recommend_addkey_match ? comiis_recommend_addkey_match[ comiis_recommend_addkey_match.length - 1 ] : null; } return ( inputFormHash || sidenv_exit_match || comiis_recommend_addkey_match ); } /** * 签到 * @param {string} _formhash_ 账号的hash值 */ function signIn(_formhash_) { function successCallBack(response) { console.log(response); GM_setValue( "mt_sign", parseInt(utils.formatTime(undefined, "yyyyMMdd")) ); if (response.lastChild || response.type == "ajax") { /* ajax函数版本 */ if (response.responseText === "") { popups.toast({ text: "签到: 成功", delayTime: 4000, }); return; } let signInContent = response.lastChild.firstChild.nodeValue; if (signInContent.includes("您已经被列入黑名单")) { popups.toast({ text: "签到: 您已经被列入黑名单", delayTime: 4000, }); return; } if (signInContent.includes("今日已签")) { popups.toast({ text: "签到: 今日已签", delayTime: 4000, }); return; } if (signInContent.includes("绑定手机号后才可以签到")) { popups.toast({ text: "签到: 绑定手机号后才可以签到", delayTime: 6000, }); return; } if ( response.responseText.includes( "您当前的访问请求当中含有非法字符,已经被系统拒绝" ) ) { popups.toast({ text: "签到: 您当前的访问请求当中含有非法字符,已经被系统拒绝", delayTime: 6000, }); return; } popups.confirm({ title: "签到的响应内容", text: response.responseText || response?.firstChild?.innerHTML, }); popups.toast({ text: "签到: 未知结果,请查看控制台信息", delayTime: 4000, }); } else { /* GM_xmlhttpRequest版本 */ let CDATA = utils.parseCDATA(response.responseText); let CDATAElement = $jq(`
    ${CDATA}
    `); let content = CDATAElement.text(); console.log(content); if (content.includes("您已经被列入黑名单")) { popups.toast({ text: "签到: 您已经被列入黑名单", delayTime: 4000, }); return; } else if (content.includes("今日已签")) { popups.toast({ text: "签到: 今日已签", delayTime: 4000, }); return; } else if (content.includes("绑定手机号后才可以签到")) { popups.toast({ text: "签到: 绑定手机号后才可以签到", delayTime: 6000, }); return; } if ( response.responseText.includes( "您当前的访问请求当中含有非法字符,已经被系统拒绝" ) ) { popups.toast({ text: "签到: 您当前的访问请求当中含有非法字符,已经被系统拒绝", delayTime: 6000, }); return; } let signIn_con = CDATAElement.find(".con"); /* 签到奖励 */ let signIn_line = CDATAElement.find(".line"); /* 签到排名 */ if (signIn_con.length && signIn_line.length) { let con = signIn_con.text().match(/([0-9]+)金币/); let line = signIn_line.text().match(/([0-9]+)/); con = con[con.length - 1]; line = line[line.length - 1]; console.log(`金币${con},排名${line}`); popups.toast({ text: `
    签到
    排名 ${line}
    金币 ${con}
    `, delayTime: 4000, }); return; } popups.confirm({ title: "签到的响应内容", text: response.responseText, }); popups.toast({ text: "签到: 未知结果,请查看控制台信息", delayTime: 4000, }); } if (typeof response === "string") { /* 无油猴函数的版本的签到成功是没有返回值的 */ popups.toast({ text: "签到: 成功", delayTime: 4000, }); return; } } function errorCalBack(response) { console.log(response); console.log("签到: 网络异常"); popups.toast({ text: "签到: 网络异常", delayTime: 4000, }); } function timeoutCallback() { console.log("签到: 网络超时"); popups.toast({ text: "签到: 网络超时", delayTime: 4000, }); } console.log("发送签到请求"); let signUrl = `https://bbs.binmt.cc/k_misign-sign.html?operation=qiandao&format=button&formhash=${_formhash_}&inajax=1&ajaxtarget=midaben_sign`; let details = { method: "GET", url: signUrl, headers: { "User-Agent": utils.getRandomPCUA(), }, timeout: 5000, onload: (response) => { successCallBack(response); }, onerror: (response) => { errorCalBack(response); }, ontimeout: () => { timeoutCallback(); }, }; if (utils.isWebView_Via()) { ajax_xmlHttpRequest(details); } else { GM_xmlhttpRequest(details); } } if (!GM_getValue("v17")) { return; } if ( envIsMobile() && window.location.href.match(DOM_CONFIG.urlRegexp.kMiSignSign) ) { if (document.querySelector(".comiis_password_top")) { GM_deleteValue("mt_sign"); popups.toast("绑定手机号后才可以签到"); return; } var deleteLocalStorageSignInfo = $jq(`
    `); deleteLocalStorageSignInfo.on("click", "i", () => { popups.confirm({ text: "

    是否清空脚本签到记录的时间?

    ", ok: { callback: () => { GM_deleteValue("mt_sign"); if (GM_getValue("mt_sign", null) != null) { popups.toast("删除失败"); } else { popups.toast("删除成功"); popups.closeMask(); popups.closeConfirm(); } }, }, mask: true, }); }); $jq(".comiis_head.f_top")?.append(deleteLocalStorageSignInfo); } if (!(await checkLogin())) { popups.toast("当前尚未登录账号"); GM_deleteValue("mt_sign"); return; } let formhash = getFormHash(); if (formhash == null) { if (document.querySelector("#comiis_picshowbox")) { /* 当前为评论区的看图模式 */ console.log("当前为评论区的看图模式 "); return; } console.log("获取账号formhash失败"); GM_deleteValue("mt_sign"); popups.toast({ text: "获取账号formhash失败", }); return; } if ( GM_getValue("mt_sign") == parseInt(utils.formatTime(undefined, "yyyyMMdd")) ) { return; } else { signIn(formhash); } }, /** * 附件点击提醒 */ attachmentClickReminder() { if (!DOM_CONFIG.methodRunCheck([DOM_CONFIG.urlRegexp.forumPost], "v57")) { return; } /** * 处理元素内的a标签的点击 * @param {HTMLElement} item */ function handleClick(item) { if (item.hasAttribute("href")) { let attachmentURL = item.getAttribute("href"); let attachmentNameNode = item.querySelector("span.f_ok"); let attachmentDownloadInfo = item.querySelector(".attach_size"); if (attachmentDownloadInfo.innerText.indexOf("金币") === -1) { return; } console.log("发现附件", item); console.log("该附件是金币附件,拦截!"); let attachmentName = attachmentNameNode.innerText; item.setAttribute("data-href", item.getAttribute("href")); item.removeAttribute("href"); attachmentNameNode.innerText = "【已拦截】" + attachmentName; item.onclick = function () { popups.confirm({ text: `
    确定花费2金币下载附件 ${attachmentName}

    `, ok: { callback: () => { console.log(attachmentURL); window.open(attachmentURL, "_blank"); popups.closeConfirm(); }, }, }); }; } } utils.mutationObserver(document.documentElement, { callback: () => { document.querySelectorAll(".attnm a").forEach((item) => { handleClick(item); }); document.querySelectorAll(".comiis_attach a").forEach((item) => { handleClick(item); }); }, config: { childList: true, subtree: true }, }); utils.waitNodeList(".attnm a").then((nodeList) => { nodeList.forEach((item) => { handleClick(item); }); }); utils.waitNodeList(".comiis_attach a").then((nodeList) => { nodeList.forEach((item) => { handleClick(item); }); }); }, /** * 自动点击同意-用户协议 */ autoClickUserAgreement() { if ( !DOM_CONFIG.methodRunCheck([ /http(s?):\/\/bbs.binmt.cc\/member.php\?mod=logging/gi, ]) ) { return; } document.querySelector("#agreebbrules")?.click(); }, /** * 小黑屋 */ blackHome() { let nextCid = ""; /* 下一个cid,用于获取下一页黑名单 */ /** * 小黑屋点击事件 */ async function blackHomeNodeClickEvent() { popups.loadingMask(); popups.toast("正在获取小黑屋名单中..."); let blackList = await getBlackList(); if (blackList.length === 0) { popups.toast("获取小黑屋名单失败"); popups.closeMask(); return; } popups.closeMask(); popups.closeToast(); let blackCSSNode = GM_addStyle(` .blackhome-user-filter input{width:-moz-available;width:-webkit-fill-available;height:30px;margin:8px 20px;border:0;border-bottom:1px solid;text-overflow:ellipsis;overflow:hidden;white-space:nowrap} .blackhome-user-list{height:350px;overflow-y:auto} .blackhome-user-list .blackhome-user-item{margin:15px 10px;padding:10px;border-radius:8px;box-shadow:0 0 .6rem #c8d0e7,-.2rem -.2rem .5rem #fff} .blackhome-user{display:flex} .blackhome-user img{width:45px;height:45px;border-radius:45px} .blackhome-user-info{margin-left:10px} .blackhome-user-info p:nth-child(1){margin-bottom:5px} .blackhome-user-info p:nth-child(2){font-size:14px} .blackhome-user-action{display:flex;margin:10px 0} .blackhome-user-action p:nth-child(1),.blackhome-user-action p:nth-child(2){border:1px solid red;color:red;border-radius:4px;padding:2px 4px;font-weight:500;font-size:14px;place-self:center} .blackhome-user-action p:nth-child(2){border:1px solid #ff4b4b;color:#ff4b4b;margin-left:8px} .blackhome-user-uuid{border:1px solid #ff7600;color:#ff7600;border-radius:4px;padding:2px 4px;font-weight:500;font-size:14px;width:fit-content;width:-moz-fit-content;margin:10px 0} .blackhome-operator{padding:10px;background-color:#efefef;border-radius:6px} .blackhome-operator-user{display:flex} .blackhome-operator-user img{width:35px;height:35px;border-radius:35px} .blackhome-operator-user p{align-self:center;margin-left:10px} .blackhome-operator-user-info{margin:10px 0;font-weight:500} `); $jq.NZ_MsgBox.confirm({ title: "小黑屋名单", content: `
    `, type: "", location: "center", buttons: { autoClose: false, reverse: true, confirm: { text: "下一页", }, cancel: { text: "关闭", }, }, callback: function (status, closeCallBack) { if (status) { blackHomeNextPageEvent(); } else { closeCallBack(); } }, }); let blackViewHTML = ""; blackList.forEach((item) => { blackViewHTML += getBlackListViewHTML(item); }); let blackViewNode = $jq(blackViewHTML); $jq(".blackhome-user-list").append(blackViewNode); setBlackHomeAvatarClickEvent(blackViewNode); setSearchPropertyChangeEvent(); } /** * 获取下一页小黑屋名单 */ async function blackHomeNextPageEvent() { popups.loadingMask(); popups.toast("正在获取小黑屋名单中..."); console.log("下一页的cid: ", nextCid); let blackList = await getBlackList(nextCid); if (blackList.length === 0) { popups.toast("获取下一页小黑屋名单失败"); popups.closeMask(); return; } popups.closeMask(); popups.closeToast(); let blackViewHTML = ""; blackList.forEach((item) => { blackViewHTML += getBlackListViewHTML(item); }); popups.toast(`成功获取 ${blackList.length}条数据`); let blackViewNode = $jq(blackViewHTML); setBlackHomeAvatarClickEvent(blackViewNode); $jq(".blackhome-user-list").append(blackViewNode); $jq(".blackhome-user-filter input")[0].dispatchEvent( new Event("propertychange") ); } /** * 设置搜索-过滤的值变化事件 */ function setSearchPropertyChangeEvent() { let isSeaching = false; $jq(".blackhome-user-filter input").on( "propertychange input", function () { let inputText = this.value.trim(); if (isSeaching) { return; } isSeaching = true; if (inputText == "") { $jq(".blackhome-user-item").each((index, item) => { item.removeAttribute("style"); }); isSeaching = false; return; } $jq(".NZ-MsgBox-alert .msgcon center").text("过滤中..."); $jq(".NZ-MsgBox-alert .msgcon center").show(); let isFind = false; $jq(".blackhome-user-item").each((index, item) => { if ( item .getAttribute("data-name") .match(new RegExp(inputText, "ig")) || item .getAttribute("data-uid") .trim() .match(new RegExp(inputText, "ig")) || item .getAttribute("data-operator") .match(new RegExp(inputText, "ig")) ) { /* 匹配到 */ isFind = true; item.removeAttribute("style"); } else { item.setAttribute("style", "display:none;"); } }); if (!isFind) { $jq(".NZ-MsgBox-alert .msgcon center").text("空"); $jq(".NZ-MsgBox-alert .msgcon center").show(); } else { $jq(".NZ-MsgBox-alert .msgcon center").hide(); } isSeaching = false; } ); } /** * 插入手机版查看小黑屋的按钮 */ async function insertMobileBlackHomeButton() { if (!DOM_CONFIG.methodRunCheck([DOM_CONFIG.urlRegexp.bbs], "v30")) { return; } let blackHomeNode = $jq(`
  • 小黑屋
  • `); GM_addStyle(` .NZ-MsgBox-alert .msgcontainer .msgtitle { text-align: center !important; }`); blackHomeNode.on("click", function () { blackHomeNodeClickEvent(); }); $jq(".comiis_sidenv_box .sidenv_li .comiis_left_Touch.bdew").append( blackHomeNode ); } /** * 获取黑名单html * @param {String} cid 下一个人的cid * @returns {String} */ function getBlackListPageInfoHTML(cid = "") { return new Promise((resolve) => { GM_xmlhttpRequest({ url: `https://bbs.binmt.cc/forum.php?mod=misc&action=showdarkroom&cid=${cid}&t=&ajaxdata=json`, timeout: 5000, method: "GET", async: false, headers: { "User-Agent": utils.getRandomPCUA(), }, onload: (response) => { console.log(response); resolve(response.responseText); }, onerror: (response) => { console.log(response); popups.toast("网络异常,请重新获取"); resolve(""); }, ontimeout: () => { popups.toast("请求超时,请重新获取"); resolve(""); }, }); }); } /** * 设置小黑屋名单中的头像点击事件 * @param {HTMLElement} blackViewNode 小黑屋元素节点 */ function setBlackHomeAvatarClickEvent(blackViewNode) { blackViewNode.on("click", ".blackhome-user img", function () { window.open( `home.php?mod=space&uid=${this.closest( ".blackhome-user-item" ).getAttribute("data-uid")}&do=profile`, "_blank" ); }); blackViewNode.on("click", ".blackhome-operator-user img", function () { window.open( `home.php?mod=space&uid=${this.closest( ".blackhome-user-item" ).getAttribute("data-operator-uid")}&do=profile`, "_blank" ); }); } /** * 获取小黑屋显示出的html * @param {Object} value * @returns */ function getBlackListViewHTML(value) { return `

    ${value["action"]}

    到期: ${value["groupexpiry"]}

    UID: ${value["uid"]}

    ${value["operator"]}

    `; } /** * 获取小黑屋名单列表 * @param {String} cid 下一页的cid */ function getBlackList(cid = "") { return new Promise(async (resolve) => { popups.toast("正在获取小黑屋名单中..."); let result = await getBlackListPageInfoHTML(cid); if (result === "" || result.startsWith("
    我的屏蔽
    `; /** * 加载本地数据到弹窗中 */ function setShieldViewData() { let shieldList = GM_getValue("shieldList", []); if (shieldList.length === 0) { $jq(".NZ-MsgBox-alert .msgcon").html("
    暂无数据
    "); return; } let shieldHTML = ""; shieldList.forEach((item) => { shieldHTML += `

    ${item["text"]}

    `; }); $jq(".NZ-MsgBox-alert .msgcon").html($jq(`
  • ${shieldHTML}
  • `)); } /** * 设置添加按钮的点击事件 * @param {Object} defaultData 默认数据 * @param {Boolean} isEdit 是否是编辑模式 */ function setAddBtnClickEvent( defaultData = { option: "user", text: "", }, isEdit = false ) { popups.confirm({ text: ` `, ok: { callback: () => { let newData = { option: $jq("#shieldSelect").val(), text: $jq("#shieldText").val(), }; let newDataString = JSON.stringify(newData); let defaultDataString = JSON.stringify(defaultData); if (utils.isNull(newData.text)) { popups.toast("请勿输入为空"); return; } if (newData.option === "uid" || newData.option === "level") { if (isNaN(newData.text)) { popups.toast("请输入正确的数字"); return; } if (newData.option === "uid" && parseInt(newData.text) < 1) { popups.toast("输入的UID不规范"); return; } } let localData = GM_getValue("shieldList", []); let sameDataCount = 0; localData.filter((item, index) => { if (JSON.stringify(item) === newDataString) { sameDataCount++; return true; } else { return false; } }); if (sameDataCount) { popups.toast("已存在相同的数据"); return; } if (isEdit) { let editStatus = false; localData.forEach((item) => { if (JSON.stringify(item) === defaultDataString) { editStatus = true; item = utils.assign(item, newData); return; } }); GM_setValue("shieldList", localData); if (editStatus) { popups.toast("修改成功"); } else { popups.toast("修改失败"); } } else { GM_setValue("shieldList", [...localData, newData]); popups.toast("添加成功"); } popups.closeMask(); popups.closeConfirm(); setShieldViewData(); }, }, }); $jq("#shieldSelect").val(defaultData["option"]); $jq("#shieldText").val(defaultData["text"]); } /** * 设置点击弹出弹窗 */ function setEvent() { $jq(document).on("click", "#ownShield", function () { $jq.NZ_MsgBox.confirm({ title: "我的屏蔽", content: "
    检索中...
    ", type: "", location: "center", buttons: { autoClose: false, reverse: true, confirm: { text: "添加", }, cancel: { text: "关闭", }, }, callback: function (status, closeCallBack) { if (status) { setAddBtnClickEvent(); } else { closeCallBack(); } }, }); setShieldViewData(); }); $jq(document).on( "click", ".NZ-MsgBox-alert .msgdivmain[data='ownShield'] i.comiis_font[data-flag='edit']", function () { let dataOption = this.closest(".msgdivmain[data=ownShield]") .getAttribute("data-option") .toString(); let dataText = this.closest(".msgdivmain[data=ownShield]") .getAttribute("data-text") .toString(); setAddBtnClickEvent( { option: dataOption, text: dataText, }, true ); } ); $jq(document).on( "click", ".NZ-MsgBox-alert .msgdivmain[data='ownShield'] i.comiis_font[data-flag='delete']", function () { let parentNode = this.parentElement; let dataOption = this.closest(".msgdivmain[data=ownShield]") .getAttribute("data-option") .toString(); let dataText = this.closest(".msgdivmain[data=ownShield]") .getAttribute("data-text") .toString(); popups.confirm({ text: "确定删除该条数据?", ok: { callback: () => { let storageItem = GM_getValue("shieldList", []); storageItem = storageItem.filter((item) => { return !( item["option"] === dataOption && item["text"] === dataText ); }); console.log(storageItem); GM_setValue("shieldList", storageItem); parentNode.remove(); popups.closeMask(); popups.closeConfirm(); popups.toast("删除成功"); }, }, }); } ); } GM_addStyle(blackListCSS); $jq(".comiis_myinfo").append($jq(blankLinesHTML)); $jq(".comiis_myinfo").append($jq(shieldUserOrPlateHTML)); setEvent(); GM_addStyle(` #blacklistallmain{height:232px} #blacklistallmain li.comiis_styli{height:180px} #blacklistallmain #blacklistuid{width:90%;resize:none;opacity:.7;height:70%!important;line-height:inherit;appearance:none;-webkit-appearance:none;border:none!important;font-size:14px;vertical-align:middle;background-color:transparent;border-bottom:3px solid #efefef!important} #blacklistallmain #blacklistplate{width:90%;resize:none;opacity:.7;height:30%!important;line-height:inherit;appearance:none;-webkit-appearance:none;border:none!important;font-size:14px;vertical-align:middle;background-color:transparent} #blacklistsave{text-align:center;background:0 0!important;border-color:transparent!important}`); }, /** * 评论过滤器 */ ownCommentsFilter() { if (window.location.href.match(DOM_CONFIG.urlRegexp.forumPost)) { let btnElement = $jq( `
  • 查看已过滤信息
  • ` ); btnElement.on("click", function () { let alertContentHTML = ""; GLOBAL_DATA.isFilterUserElementList.forEach((item) => { alertContentHTML += item; }); alertContentHTML = `
    ${alertContentHTML}
    `; $jq.NZ_MsgBox.alert({ title: "评论过滤器-已过滤信息", type: "", content: alertContentHTML, location: "center", buttons: { autoClose: true, confirm: { text: "关闭", }, }, }); }); $jq("#comiis_foot_gobtn .comiis_shareul.swiper-wrapper").append( btnElement ); } if (!DOM_CONFIG.methodRunCheck([DOM_CONFIG.urlRegexp.homeSpaceUrl])) { return; } const ownCommentsFilterCSS = ` #commentsFilter{border-radius:0} #commentsFilter a{border-top: 1px solid #efefef !important;} #commentsFilter a .styli_tit i{color:#ff0019!important} `; const ownCommentsFilterDialogCSS = ` textarea.msgbox-comments-filter-content{border:none;outline:0;padding:0;margin:0;-webkit-appearance:none;-moz-appearance:none;appearance:none;background-image:none;background-color:transparent} textarea.msgbox-comments-filter-content{width:100%;height:380px;display:inline-block;resize:vertical;padding:5px 15px;line-height:1.5;box-sizing:border-box;color:#606266;background-color:#fff;border:1px solid #dcdfe6;border-radius:4px;transition:border-color .2s cubic-bezier(.645,.045,.355,1)} textarea.msgbox-comments-filter-content:hover{border-color:#c0c4cc} textarea.msgbox-comments-filter-content:focus{border-color:#3677f0} `; const ownCommentsFilterHTML = ` `; GM_addStyle(ownCommentsFilterCSS); GM_addStyle(ownCommentsFilterDialogCSS); $jq(".comiis_myinfo").append($jq(ownCommentsFilterHTML)); /* 添加点击事件 */ $jq("#commentsFilter").on("click", function () { $jq.NZ_MsgBox.confirm({ title: "评论过滤器", content: ` `, type: "", location: "center", buttons: { autoClose: false, reverse: true, confirm: { text: "添加", }, cancel: { text: "关闭", }, }, callback: function (status, closeCallBack) { if (!status) { closeCallBack(); return; } try { let userInputData = $jq("textarea.msgbox-comments-filter-content") .val() .trim(); if (userInputData === "") { GM_deleteValue("ownCommentsFilterData"); popups.toast("恢复默认"); closeCallBack(); return; } let formatUserInputData = JSON.parse(userInputData); let mustParamList = [ "replyFlag", "avatarFlag", "minLength", "keywords", "userBlackList", "userWhiteList", ]; for (const mustParamName of mustParamList) { if (typeof formatUserInputData[mustParamName] === "undefined") { popups.toast("缺失参数:" + mustParamName); return; } } if (!Array.isArray(formatUserInputData["keywords"])) { popups.toast("参数keywords必须是数组"); return; } if (!Array.isArray(formatUserInputData["userBlackList"])) { popups.toast("参数keywords必须是数组"); return; } if (!Array.isArray(formatUserInputData["userWhiteList"])) { popups.toast("参数keywords必须是数组"); return; } GM_setValue("ownCommentsFilterData", formatUserInputData); popups.toast("设置成功"); closeCallBack(); } catch (error) { popups.toast({ text: "数据格式验证失败:" + error.toString(), delayTime: 5000, }); } }, }); let ownCommentsFilterData = GM_getValue( "ownCommentsFilterData", DEFAULT_CONFIG.ownCommentsFilterData ); $jq("textarea.msgbox-comments-filter-content").val( JSON.stringify(ownCommentsFilterData, undefined, 2) ); }); }, /** * 在聊天的插入的图片图床接口API */ chartBed: { ret_code: { 200: { 200: "删除成功", }, 500: { 101: "重复上传", 400: "请求被拒绝,token错误", 401: "请求被拒绝", }, 400: { 100: "删除失败,图片已删除", 101: "重复上传", }, }, storage: { /** * 对已上传图片添加上传记录到本地存储 * @param {*} web * @param {*} id_encoded * @param {*} url * @param {*} thumb_url * @param {*} name */ add: function (web, id_encoded, url, thumb_url, name) { let localData = GM_getValue("chartBedsImagesHistory", []); let saveData = localData.concat({ web: web, id_encoded: id_encoded, url: url, thumb_url: thumb_url, name: name, }); GM_setValue("chartBedsImagesHistory", saveData); }, /** * 删除本地存储中已上传图片的记录 * @param {*} _web_ * @param {*} id_encoded * @returns */ delete: function (_web_, id_encoded) { let localData = GM_getValue("chartBedsImagesHistory", []); let successDelete = false; Array.from(localData).forEach((item, index) => { if (item["web"] == _web_ && item["id_encoded"] == id_encoded) { successDelete = true; localData.splice(index, 1); GM_setValue("chartBedsImagesHistory", localData); return; } }); console.log("删除数据:", successDelete); if (!successDelete) { popups.toast("删除数据失败"); } return successDelete; }, /** * 获取本地存储中已上传的图片信息 * @returns */ get: function () { return GM_getValue("chartBedsImagesHistory", []); }, }, /** * 获取图床的auth_token,这里是想imgtu或hello图床这些通用api接口 * @param {*} url * @returns */ getAuthToken(url) { return new Promise((resolve) => { GM_xmlhttpRequest({ url: url, method: "GET", timeout: 15000, responseType: "html", headers: { "User-Agent": utils.getRandomPCUA(), }, onload: (response) => { let token = response.responseText.match( /PF.obj.config.auth_token[\s]*=[\s]*"(.+)";/i ); if (token != null && token.length == 2) { popups.toast("auth_token成功获取"); resolve(token[1]); } else { console.log(response); popups.toast("auth_token获取失败"); resolve(null); } }, onerror: () => { popups.toast("网络异常"); resolve(null); }, ontimeout: () => { popups.toast("请求超时"); resolve(null); }, }); }); }, /** * 图床登录 * @param {string} url 地址 * @param {string} user 用户名 * @param {string} pwd 密码 * @param {string} auth_token 验证token * @async */ login(url, user, pwd, auth_token) { return new Promise((resolve) => { GM_xmlhttpRequest({ url: `${url}/login`, method: "POST", timeout: 6000, data: `login-subject=${user}&password=${pwd}&auth_token=${auth_token}`, headers: { "Content-Type": "application/x-www-form-urlencoded", "User-Agent": utils.getRandomPCUA(), }, onload: function (response) { console.log(response); if ( response.status == 200 && response.responseText.match("注销") ) { console.log("登陆成功"); popups.toast("登陆成功"); resolve(true); } else { console.log("登录失败"); popups.toast("登录失败"); resolve(false); } }, onerror: (response) => { console.log("网络异常", response); popups.toast("网络异常"); resolve(false); }, ontimeout: () => { console.log("请求超时"); popups.toast("请求超时"); resolve(false); }, }); }); }, /** * 上传图片 * @param {string} url * @param {string} auth_token * @param {File} imageFile * @returns */ uploadImage(url, auth_token, imageFile) { let res_data = { imageUri: null, json_data: null, }; let form = new FormData(); form.append("type", "file"); form.append("action", "upload"); form.append("timestamp", new Date().getTime()); form.append("auth_token", auth_token); form.append("nsfw", 0); form.append("source", imageFile); return new Promise((resolve) => { GM_xmlhttpRequest({ url: `${url}/json`, method: "POST", data: form, async: false, headers: { Accept: "application/json", "User-Agent": utils.getRandomPCUA(), Referer: `${url}/`, Origin: url, }, onload: (response) => { console.log(response); let json_data = null; try { json_data = JSON.parse(response.responseText); console.log(json_data); } catch (error) { popups.toast("上传失败,请看控制台:" + error); resolve(res_data); return; } let status_code = json_data["status_code"]; if (status_code == 200) { popups.toast("上传成功"); let file_reader = new FileReader(); /* FileReader主要用于将文件内容读入内存,通过一系列异步接口,可以在主线程中访问本地文件 */ file_reader.readAsDataURL( imageFile ); /* 读取图片的内容生成的base64编码的图 */ /* 读取完成后,执行该回调函数,它会返回读取的结果result */ file_reader.onload = function () { let imageUri = this.result; /* 此时的图片已经存储到了result中 */ res_data["imageUri"] = imageUri; res_data["json_data"] = json_data; resolve(res_data); }; } else if ( mobile.chartBed.ret_code[status_code] != null && mobile.chartBed.ret_code[status_code][ json_data["error"]["code"] ] != null ) { popups.toast( mobile.chartBed.ret_code[status_code][ json_data["error"]["code"] ] ); resolve(res_data); } else { console.log(json_data); resolve(res_data); } }, onerror: (response) => { console.log(response); popups.toast("网络异常"); resolve(res_data); }, }); }); }, /** * 删除已上传图片 * @param {*} url * @param {*} auth_token * @param {*} id_encoded * @returns */ deleteImage(url, auth_token, id_encoded) { return new Promise((resolve) => { GM_xmlhttpRequest({ url: `${url}/json`, method: "POST", timeout: 15000, data: `auth_token=${auth_token}&action=delete&single=true&delete=image&deleting[id]=${id_encoded}`, headers: { "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8", "User-Agent": utils.getRandomPCUA(), }, onload: (response) => { try { let json_data = JSON.parse(response.responseText); let status_code = json_data["status_code"]; if (status_code == 200 && json_data["success"]["code"] == 200) { popups.toast(mobile.chartBed.ret_code["200"]["200"]); resolve(true); } else if ( status_code == 400 && json_data["error"]["code"] == 100 ) { popups.toast(mobile.chartBed.ret_code["400"]["100"]); resolve(true); } else if ( mobile.chartBed.ret_code[status_code] != null && mobile.chartBed.ret_code[status_code][ json_data["error"]["code"] ] != null ) { popups.toast( mobile.chartBed.ret_code[status_code][ json_data["error"]["code"] ] ); resolve(false); } else { console.log(json_data); popups.toast(json_data["error"]["message"]); resolve(false); } } catch (error) { popups.toast("删除失败"); console.log(error); resolve(false); } }, onerror: () => { popups.toast("网络异常"); resolve(false); }, ontimeout: () => { popups.toast("请求超时"); resolve(false); }, }); }); }, /** * 图片账号密码的弹窗 * @param {*} chartbedname * @param {*} register_url * @param {*} callbackfun */ popupUserPwd(chartbedname, register_url, callbackfun) { popups.confirm({ text: `

    ${chartbedname}

    `, mask: true, only: true, ok: { callback: () => { let inputUser = document .querySelector("#chartbed_user") .value.trim(); let inputPwd = document .querySelector("#chartbed_pwd") .value.trim(); callbackfun(inputUser, inputPwd); }, }, }); }, }, /** * 聊天的图床 */ chatChartBed() { if (!DOM_CONFIG.methodRunCheck([DOM_CONFIG.urlRegexp.chatUrl], "v40")) { return; } GM_addStyle(` .comiis_post_imglist li.up_btn_hello a,.comiis_post_imglist li.up_btn_kggzs a,.comiis_post_imglist li.up_btn_z4a a{display:block;width:50px;height:50px;line-height:50px;padding:4px;border-radius:2px;border-style:dashed} .comiis_post_imglist li.up_btn_hello a i,.comiis_post_imglist li.up_btn_kggzs a i,.comiis_post_imglist li.up_btn_z4a a i{position:absolute;top:11px;left:5px;z-index:8;font-size:26px;width:50px;height:50px;line-height:50px;text-align:center} .comiis_post_imglist li.up_btn_hello a input,.comiis_post_imglist li.up_btn_kggzs a input,.comiis_post_imglist li.up_btn_z4a a input{position:absolute;top:11px;left:5px;height:50px;width:50px;z-index:10;opacity:0} .comiis_post_imglist li .delImg{position:absolute;top:-5px;left:-5px} .comiis_post_imglist li .delImg i{font-size:24px;background:#fff;border-radius:50%} .imgboxlist{height:170px;overflow-y:auto} .menuclicked{background:#fff} #filedata_hello,#filedata_kggzs,#filedata_z4a{display:none} `); function chatKGChartBed() { /* 聊天快捷图片上传康哥图床 */ let chartBedUrl = "https://img.kggzs.cn/api/v1"; let chartBedUser = GM_getValue("KggzsChartBedUser"); let chartBedPwd = GM_getValue("KggzsChartBedPwd"); let chartBedToken = null; let loginStatus = false; /* 登录状态 */ let tokenStatus = false; /* token状态 */ let code = { 401: "未登录或授权失败", 403: "管理员关闭了接口功能", 429: "超出请求配额,请求受限", 500: "服务端出现异常", }; function getToken() { return new Promise((resolve) => { GM_xmlhttpRequest({ url: `${chartBedUrl}/tokens`, method: "POST", timeout: 5000, data: `email=${chartBedUser}&password=${chartBedPwd}`, headers: { Accept: "application/json", "User-Agent": utils.getRandomPCUA(), }, onload: (response) => { if (code[response.status] != null) { popups.toast(code[response.status]); resolve(null); return; } let json_data = JSON.parse(response.responseText); if (json_data["status"]) { popups.toast("token成功获取"); resolve(json_data["data"]["token"]); } else { popups.toast(json_data["message"]); resolve(null); } }, onerror: () => { popups.toast("网络异常"); resolve(null); }, ontimeout: () => { popups.toast("请求超时"); resolve(null); }, }); }); } function uploadImage(imageFile) { let res_data = { imageUri: null, json_data: null, }; let form = new FormData(); form.append("strategy_id", 2); /* 存储策略 */ form.append("file", imageFile); return new Promise((resolve) => { GM_xmlhttpRequest({ url: `${chartBedUrl}/upload`, method: "POST", data: form, async: false, headers: { Accept: "application/json", "User-Agent": utils.getRandomPCUA(), Authorization: `Bearer ${chartBedToken}`, }, onload: (response) => { if (code[response.status] != null) { popups.toast(code[response.status]); resolve(res_data); return; } let json_data = JSON.parse(response.responseText); console.log(json_data); if (json_data["status"]) { popups.toast("上传成功"); let file_reader = new FileReader(); /* FileReader主要用于将文件内容读入内存,通过一系列异步接口,可以在主线程中访问本地文件 */ file_reader.readAsDataURL( imageFile ); /* 读取图片的内容生成的base64编码的图 */ /* 读取完成后,执行该回调函数,它会返回读取的结果result */ file_reader.onload = function () { let imageUri = this.result; /* 此时的图片已经存储到了result中 */ res_data["imageUri"] = imageUri; res_data["json_data"] = json_data; resolve(res_data); }; } else { console.log(json_data); popups.toast(json_data["message"]); resolve(res_data); } }, onerror: () => { popups.toast("网络异常"); resolve(res_data); }, }); }); } function deleteImage(imageKey) { return new Promise((resolve) => { GM_xmlhttpRequest({ url: `${chartBedUrl}/images/:${imageKey}`, method: "DELETE", async: false, timeout: 5000, data: JSON.stringify({ key: "", }), headers: { Accept: "application/json", "User-Agent": utils.getRandomPCUA(), Referer: `${chartBedUrl}/`, Authorization: `Bearer ${chartBedToken}`, Origin: chartBedUrl, }, onload: (response) => { if (code[response.status] != null) { popups.toast(code[response.status]); resolve(res_data); return; } let json_data = JSON.parse(response.responseText); console.log(json_data); }, onerror: () => { popups.toast("网络异常"); resolve(res_data); }, ontimeout: () => { popups.toast("请求超时"); resolve(res_data); }, }); }); } function clearData() { chartBedUser = ""; chartBedPwd = ""; chartBedToken = null; loginStatus = false; tokenStatus = false; GM_deleteValue("KggzsChartBedUser"); GM_deleteValue("KggzsChartBedPwd"); } $jq(document).on( "click", "#imglist_kggzs .up_btn_kggzs a", async function () { if (tokenStatus) { popups.toast("正在配置中..."); return; } if (!chartBedUser || !chartBedPwd) { let loginCallBack = () => { let user = $jq("#chartbed_user").val().trim(); let pwd = $jq("#chartbed_pwd").val().trim(); if (user && pwd) { GM_setValue("KggzsChartBedUser", user); GM_setValue("KggzsChartBedPwd", pwd); chartBedUser = user; chartBedPwd = pwd; popups.closeConfirm(); setTimeout(() => { $jq("#imglist_kggzs .up_btn_kggzs a").click(); }, 500); } else { popups.toast("账号或密码不能为空"); } }; mobile.chartBed.popupUserPwd( "康哥图床", "https://img.kggzs.cn/register", loginCallBack ); } else if (chartBedToken == null || !loginStatus) { popups.loadingMask(); tokenStatus = true; popups.toast("正在配置token"); chartBedToken = await getToken(); popups.closeMask(); console.log("token:" + chartBedToken); if (chartBedToken != null) { $jq("#filedata_kggzs").click(); } else { clearData(); } tokenStatus = false; } else { $jq("#filedata_kggzs").click(); } } ); $jq(document).on("change", "#filedata_kggzs", (event) => { let chooseImageFiles = event.currentTarget.files; if (chooseImageFiles.length == 0) { return; } popups.loadingMask(); popups.toast("上传图片中...请稍后"); console.log(`图片数量:${chooseImageFiles.length}`); let uploadFileAwaitFunction = async (chooseImageFileItemIndex) => { let imageFile = chooseImageFiles[chooseImageFileItemIndex]; console.log("上传图片:", imageFile); let uploadImageReturn = await uploadImage(imageFile); if (uploadImageReturn["json_data"] != null) { console.log(uploadImageReturn); let image_id_encoded = uploadImageReturn["json_data"]["data"]["key"]; let image_url = uploadImageReturn["json_data"]["data"]["links"]["url"]; let image_thumb_url = uploadImageReturn["json_data"]["data"]["links"][ "thumbnail_url" ]; let image_name = uploadImageReturn["json_data"]["data"]["origin_name"]; let image_uri = uploadImageReturn["imageUri"]; let uploadImageHTML = `
  • 插入
  • `; $jq("#imglist_kggzs").append($jq(uploadImageHTML)); mobile.chartBed.storage.add( "kggzs", image_id_encoded, image_url, image_thumb_url, image_name ); } }; let completeFunction = () => { popups.closeMask(); $jq("#filedata_kggzs").val(""); }; utils .waitArrayLoopToEnd(chooseImageFiles, uploadFileAwaitFunction) .then(() => { utils.tryCatch().run(completeFunction); }); }); $jq(document).on( "click", "#imglist_kggzs .delImg", async function (event) { utils.preventEvent(event); event.currentTarget.parentElement.remove(); /* popups.toast('删除中,请稍后'); let id_encoded = e.currentTarget.getAttribute("id-encode"); if(!id_encoded){ popups.toast('获取id_encoded失败,请自行去Hello图床删除'); return; } let deleteStatus = await deleteImage(key); if(deleteStatus){ e.currentTarget.parentElement.remove(); mobile.chartBed.storage.delete("kggzs",id_encoded); } */ } ); } function chatHelloChartBed() { /* 聊天快捷图片上传Hello图床 */ let chartBedUrl = "https://www.helloimg.com"; let chartBedUser = GM_getValue("HelloChartBedUser"); let chartBedPwd = GM_getValue("HelloChartBedPwd"); let chartBedAuthToken = null; let loginStatus = false; /* 登录状态 */ let authTokenStatus = false; /* authToken状态 */ let clearData = () => { GM_deleteValue("HelloChartBedUser"); GM_deleteValue("HelloChartBedPwd"); loginStatus = false; authTokenStatus = false; chartBedUser = ""; chartBedPwd = ""; chartBedAuthToken = null; }; $jq(document).on( "click", "#imglist_hello .up_btn_hello a", async function () { if (authTokenStatus) { popups.toast("正在配置中..."); return; } if (!chartBedUser || !chartBedPwd) { let loginCallBack = () => { let user = $jq("#chartbed_user").val().trim(); let pwd = $jq("#chartbed_pwd").val().trim(); if (user && pwd) { GM_setValue("HelloChartBedUser", user); GM_setValue("HelloChartBedPwd", pwd); chartBedUser = user; chartBedPwd = pwd; popups.closeConfirm(); setTimeout(() => { $jq("#imglist_hello .up_btn_hello a").click(); }, 500); } else { popups.toast("账号或密码不能为空"); } }; mobile.chartBed.popupUserPwd( "Hello图床", "https://www.helloimg.com/signup", loginCallBack ); } else if (chartBedAuthToken == null || !loginStatus) { authTokenStatus = true; popups.loadingMask(); popups.toast("正在配置auth_token"); chartBedAuthToken = await mobile.chartBed.getAuthToken( chartBedUrl ); console.log("auth_token:", chartBedAuthToken); if (chartBedAuthToken != null) { popups.toast("正在登录Hello图床"); let retloginStatus = await mobile.chartBed.login( chartBedUrl, chartBedUser, chartBedPwd, chartBedAuthToken ); popups.closeMask(); if (retloginStatus) { loginStatus = true; $jq("#filedata_hello").click(); } else if (retloginStatus == false) { clearData(); } } popups.closeMask(); authTokenStatus = false; } else { $jq("#filedata_hello").click(); } } ); $jq(document).on("change", "#filedata_hello", (event) => { let chooseImageFiles = event.currentTarget.files; if (chooseImageFiles.length == 0) { return; } popups.loadingMask(); popups.toast("上传图片中...请稍后"); let uploadFileAwaitFunction = async (chooseImageFileItemIndex) => { let imageFile = chooseImageFiles[chooseImageFileItemIndex]; console.log("上传图片:", imageFile); let uploadImageReturn = await mobile.chartBed.uploadImage( chartBedUrl, chartBedAuthToken, imageFile ); if (uploadImageReturn["json_data"] != null) { let image_id_encoded = uploadImageReturn["json_data"]["image"]["id_encoded"]; let image_url = uploadImageReturn["json_data"]["image"]["url"]; let image_thumb_url = uploadImageReturn["json_data"]["image"]["thumb"]["url"]; let image_name = uploadImageReturn["json_data"]["image"]["filename"]; let image_uri = uploadImageReturn["imageUri"]; let uploadImageHTML = `
  • 插入
  • `; $jq("#imglist_hello").append($jq(uploadImageHTML)); mobile.chartBed.storage.add( "hello", image_id_encoded, image_url, image_thumb_url, image_name ); } }; let completeFunction = () => { popups.closeMask(); $jq("#filedata_hello").val(""); }; utils .waitArrayLoopToEnd(chooseImageFiles, uploadFileAwaitFunction) .then(() => { utils.tryCatch().run(completeFunction); }); }); $jq(document).on( "click", "#imglist_hello .delImg", async function (event) { utils.preventEvent(event); popups.loadingMask(); popups.toast("删除中,请稍后"); let id_encoded = event.currentTarget.getAttribute("id-encode"); if (!id_encoded) { popups.closeMask(); popups.toast("获取id_encoded失败,请自行去Hello图床删除"); return; } let deleteStatus = await mobile.chartBed.deleteImage( chartBedUrl, chartBedAuthToken, id_encoded ); popups.closeMask(); if (deleteStatus) { $jq(this).parent().remove(); mobile.chartBed.storage.delete("hello", id_encoded); } } ); } function chatZ4AChartBed() { /* 聊天快捷图片上传Z4A图床 */ let chartBedUrl = "https://www.z4a.net"; let chartBedUser = GM_getValue("Z4AChartBedUser"); let chartBedPwd = GM_getValue("Z4AChartBedPwd"); let chartBedAuthToken = null; let loginStatus = false; /* 登录状态 */ let authTokenStatus = false; /* authToken状态 */ let clearData = () => { GM_deleteValue("Z4AChartBedUser"); GM_deleteValue("Z4AChartBedPwd"); loginStatus = false; authTokenStatus = false; chartBedUser = ""; chartBedPwd = ""; chartBedAuthToken = null; }; $jq(document).on( "click", "#imglist_z4a .up_btn_z4a a", async function () { if (authTokenStatus) { popups.toast("正在配置中..."); return; } if (!chartBedUser || !chartBedPwd) { let loginCallBack = () => { let user = $jq("#chartbed_user").val().trim(); let pwd = $jq("#chartbed_pwd").val().trim(); if (user && pwd) { GM_setValue("Z4AChartBedUser", user); GM_setValue("Z4AChartBedPwd", pwd); chartBedUser = user; chartBedPwd = pwd; popups.closeConfirm(); setTimeout(() => { $jq("#imglist_z4a .up_btn_z4a a").click(); }, 500); } else { popups.toast("账号或密码不能为空"); } }; mobile.chartBed.popupUserPwd( "Z4A图床", "https://www.z4a.net/signup", loginCallBack ); } else if (chartBedAuthToken == null || !loginStatus) { popups.loadingMask(); authTokenStatus = true; popups.toast("正在配置auth_token"); chartBedAuthToken = await mobile.chartBed.getAuthToken( chartBedUrl ); console.log("auth_token:", chartBedAuthToken); if (chartBedAuthToken != null) { popups.toast("正在登录Z4A图床"); let retloginStatus = await mobile.chartBed.login( chartBedUrl, chartBedUser, chartBedPwd, chartBedAuthToken ); popups.closeMask(); if (retloginStatus) { loginStatus = true; $jq("#filedata_z4a").click(); } else if (retloginStatus == false) { clearData(); } } popups.closeMask(); authTokenStatus = false; } else { $jq("#filedata_z4a").click(); } } ); $jq(document).on("change", "#filedata_z4a", async (event) => { let chooseImageFiles = event.currentTarget.files; if (chooseImageFiles.length == 0) { return; } popups.loadingMask(); popups.toast("上传图片中...请稍后"); let uploadFileAwaitFunction = async (chooseImageFileItemIndex) => { let imageFile = chooseImageFiles[chooseImageFileItemIndex]; console.log("上传图片:", imageFile); let uploadImageReturn = await mobile.chartBed.uploadImage( chartBedUrl, chartBedAuthToken, imageFile ); if (uploadImageReturn["json_data"] != null) { let image_id_encoded = uploadImageReturn["json_data"]["image"]["id_encoded"]; let image_url = uploadImageReturn["json_data"]["image"]["url"]; let image_thumb_url = uploadImageReturn["json_data"]["image"]["thumb"]["url"]; let image_name = uploadImageReturn["json_data"]["image"]["filename"]; let image_uri = uploadImageReturn["imageUri"]; let uploadImageHTML = `
  • 插入
  • `; $jq("#imglist_z4a").append($jq(uploadImageHTML)); mobile.chartBed.storage.add( "z4a", image_id_encoded, image_url, image_thumb_url, image_name ); } }; let completeFunction = () => { popups.closeMask(); $jq("#filedata_z4a").val(""); }; utils .waitArrayLoopToEnd(chooseImageFiles, uploadFileAwaitFunction) .then(() => { utils.tryCatch().run(completeFunction); }); }); $jq(document).on( "click", "#imglist_z4a .delImg", async function (event) { utils.preventEvent(event); popups.loadingMask(); popups.toast("删除中,请稍后"); let id_encoded = event.currentTarget.getAttribute("id-encode"); if (!id_encoded) { popups.closeMask(); popups.toast("获取id_encoded失败,请自行去Z4A图床删除"); return; } let deleteStatus = await mobile.chartBed.deleteImage( chartBedUrl, chartBedAuthToken, id_encoded ); popups.closeMask(); if (deleteStatus) { $jq(this).parent().remove(); mobile.chartBed.storage.delete("z4a", id_encoded); } } ); } function chatHistoryChartBedImages() { /* 所有图床历史上传过的图片 */ let historyImages = mobile.chartBed.storage.get(); $jq.each(historyImages, (i) => { let _web = historyImages[i]["web"]; let _url = historyImages[i]["url"]; let _thumb_url = historyImages[i]["thumb_url"]; let _name = historyImages[i]["name"]; let _imageHTML = `
  • ${_web}
  • `; $jq("#imglist_history").append($jq(_imageHTML)); }); $jq("#menu_chartbed_history").on("click", function () { $jq.each($jq("#imglist_history li img"), (index, item) => { if (!item.getAttribute("src")) { item.setAttribute("src", item.getAttribute("data-src")); } }); }); $jq("#imglist_history").on("click", ".delImg", async (event) => { utils.preventEvent(event); let _t_index = event.currentTarget.getAttribute("t-index"); let imageItem = historyImages[_t_index]; let web = imageItem["web"]; let id_encoded = imageItem["id_encoded"]; event.currentTarget.parentElement.remove(); mobile.chartBed.storage.delete(web, id_encoded); }); } let imgBtn = ``; let menu = ``; $jq(".styli_tit.comiis_post_ico.f_c.cl").append($jq(imgBtn)); $jq("#comiis_post_tab").append($jq(menu)); let imgUploadBtn = ` `; let imgMenu = `
  • 康哥图床
  • hello图床
  • z4a图床
  • 历史图片
  • `; $jq("#comiis_img_chartbed_key").append($jq(imgMenu)); $jq(".comiis_minibq .imgboxlist").append($jq(imgUploadBtn)); $jq("#comiis_img_chartbed_key li").on("click", function () { $jq("#comiis_img_chartbed_key li").removeClass("bg_f"); $jq(this).addClass("bg_f"); $jq("#comiis_post_tab .imgboxlist .comiis_upbox") .hide() .eq($jq(this).index()) .fadeIn(); }); if (GM_getValue("chartBedsImagesHistory") == undefined) { GM_setValue("chartBedsImagesHistory", []); } utils.tryCatch().run(chatKGChartBed); utils.tryCatch().run(chatHelloChartBed); utils.tryCatch().run(chatZ4AChartBed); utils.tryCatch().run(chatHistoryChartBedImages); }, /** * 每7天清理回复框记录的数据 */ clearLocalReplyData() { if (!GM_getValue("v58")) { return; } let lastClearReplyRecordDataTime = GM_getValue( "lastClearReplyRecordDataTime" ); if (lastClearReplyRecordDataTime) { let daysDifference = utils.getDaysDifference( lastClearReplyRecordDataTime ); console.log( `上次清除的时间: ${utils.formatTime( lastClearReplyRecordDataTime )} 间隔: ${daysDifference}天` ); if (daysDifference < 7) { /* 少于7天就不清除 */ return; } } let db = new utils.indexedDB("mt_reply_record", "input_text"); db.deleteAll().then((resolve) => { console.log(resolve); GM_setValue("lastClearReplyRecordDataTime", new Date().getTime()); }); }, /** * 帖子快照 */ customCollection() { if ( !DOM_CONFIG.methodRunCheck( [DOM_CONFIG.urlRegexp.bbs, DOM_CONFIG.urlRegexp.forumPost], "v54" ) ) { return; } const urlBBSMatchStatus = window.location.href.match( DOM_CONFIG.urlRegexp.bbs ); const forumPostMatchStatus = window.location.href.match( DOM_CONFIG.urlRegexp.forumPost ); const collectTime = Date.now(); const DB_NAME = "mt_db", DB_STORE_NAME = "custom_collection", DB_STORE_KEY_NAME = "forum_post_" + utils.formatTime(collectTime, "yyyy_MM_dd_HH_mm_ss"); var db = new utils.indexedDB(DB_NAME, DB_STORE_NAME); async function showView() { /* 显示-快照列表(dialog) */ $jq.NZ_MsgBox.alert({ title: "快照", content: "
    获取中...
    ", type: "", location: "center", buttons: { confirm: { text: "确定", }, }, }); var matchRegexp = new RegExp("forum_post_", "gi"); db.regexpGet(matchRegexp).then((resolve) => { if (resolve["code"] !== 200) { popups.toast({ text: resolve["msg"], }); return; } var customCollectionData = resolve["data"]; if (customCollectionData.length) { console.log(customCollectionData); utils.sortListByProperty(customCollectionData, "timestamp", true); console.log("排序后——快照:", customCollectionData); $jq(".msgcon").html(""); $jq(".msgcon").append( '
    ' ); var customTableTdWidth = $jq(".msgcon").width() ? $jq(".msgcon").width() - 50 : 240; customCollectionData.forEach((item, index) => { var itemElement = $jq(` `); itemElement.find("a[t-blank]").on("click", function () { window.open(item["url"], "_blank"); }); itemElement.find("a[t-dialog]").on("click", function () { if (item["type"] === "html") { var pageBlob = new Blob([item["data"]], { type: "text/html", }); xtip.open({ type: "html", width: document.documentElement.clientWidth + "px", height: document.documentElement.clientHeight + "px", content: ``, title: "查看帖子快照", lock: false, zindex: parseInt($jq(".NZ-MsgBox-alert").css("z-index")) + 100, }); } else { xtip.open({ type: "html", width: document.documentElement.clientWidth + "px", height: document.documentElement.clientHeight + "px", content: ``, title: "查看帖子快照", lock: false, zindex: parseInt($jq(".NZ-MsgBox-alert").css("z-index")) + 100, }); } }); itemElement.find(".delsubjecttip").on("click", function () { let that = this; popups.confirm({ text: "

    确定删除该快照?

    ", mask: true, ok: { callback: () => { console.log("删除:", item["key"]); db.delete(item["key"]).then( (resolve) => { if (resolve["code"] !== 200) { popups.toast({ text: resolve["msg"], }); popups.closeConfirm(); return; } customCollectionData.forEach((_item_, _index_) => { if (_item_["key"] === item["key"]) { customCollectionData.splice(_index_, 1); } }); console.log("移出后:", customCollectionData); popups.toast({ text: "删除成功", }); utils.deleteParentNode(that, "#autolist"); popups.closeConfirm(); }, (err) => { console.log(err); popups.closeConfirm(); popups.toast({ text: "删除失败,原因请看控制台", }); } ); }, }, only: true, }); }); $jq(".msgcon").css("height", "400px"); $jq(".msgcon #misign_list").append(itemElement); }); } else { $jq(".msgcon").html("
    暂无快照
    "); } }), (err) => { console.log(err); }; } function insertLeftButton() { /* 插入左边按钮 */ var collectLeftBtnElement = $jq(`
  • 查看快照
  • `); collectLeftBtnElement.find("a").on("click", function () { showView(); }); $jq(".comiis_sidenv_box .sidenv_li .comiis_left_Touch.bdew").append( collectLeftBtnElement ); } function insertTopButton() { /* 插入帖子内部快照按钮 */ var collectPageBtnElement = $jq( `
  • 快照
  • ` ); collectPageBtnElement.find("a").on("click", function () { $jq(".comiis_share_box_close")?.click(); xtip.sheet({ btn: ["快照为图片", "快照为源码"], btn1: function () { popups.loadingMask(); popups.toast({ text: "正在处理网页转图片中", }); var html2canvasOptions = { allowTaint: true, logging: true, useCORS: true, ignoreElements: (element) => { /*遍历每个节点*/ if ( element.id === "comiis_bgbox" /* 点击右上角三个按钮的背景遮罩层 */ || element.id === "comiis_foot_more" /* 点击右上角三个按钮后出现的菜单栏 */ || element.id === "force-mask" /* popups的遮罩层 */ || element.className === "popups-toast" /* toast弹窗 */ || element.id === "comiis_foot_menu_beautify" /* 底部回复框 */ || element.id === "comiis_head" /* 顶部一栏 */ || (typeof element.className === "string" && element.className.indexOf("xtiper_win_fixed ") != -1) ) return true; }, }; html2canvas(document.documentElement, html2canvasOptions).then( (canvas) => { var base64Image = canvas.toDataURL("image/png"); popups.toast({ text: "转换完毕,正在保存数据", }); var data = { type: "image", url: window.location.href, title: document.title.replace(" - MT论坛", ""), data: base64Image, time: utils.formatTime(collectTime), timestamp: collectTime, }; db.save(DB_STORE_KEY_NAME, data).then((resolve) => { console.log(resolve); if (resolve["code"] !== 200) { console.log(resolve); popups.closeMask(); popups.toast({ text: resolve["msg"], }); return; } popups.closeMask(); popups.toast({ text: "保存成功", }); }), (err) => { console.log(err); popups.closeMask(); popups.toast({ text: "保存数据失败", }); }; } ); }, btn2: function () { popups.loadingMask(); popups.toast({ text: "正在保存数据中", }); var jqHTML = $jq("html"); jqHTML.find("#force-mask")?.remove(); jqHTML.find(".xtiper_win_fixed")?.remove(); jqHTML.css("overflow", "auto"); var pageHTML = jqHTML.prop("outerHTML"); var data = { type: "html", url: window.location.href, title: document.title.replace(" - MT论坛", ""), data: pageHTML, time: utils.formatTime(collectTime), timestamp: collectTime, }; db.save(DB_STORE_KEY_NAME, data).then((resolve) => { console.log(resolve); if (resolve["code"] !== 200) { console.log(resolve); popups.closeMask(); popups.toast({ text: resolve["msg"], }); return; } popups.closeMask(); popups.toast({ text: "保存成功", }); }), (err) => { console.log(err); popups.closeMask(); popups.toast({ text: "保存数据失败", }); }; }, }); }); $jq("#comiis_foot_gobtn .comiis_shareul.swiper-wrapper").append( collectPageBtnElement ); } if (urlBBSMatchStatus) { console.log("插入查看快照按钮"); insertLeftButton(); } if (forumPostMatchStatus) { insertTopButton(); } }, /** * 编辑器的图床 */ editorChartBed() { /** * 论坛图床-修复点击上传和点击插入功能 */ function chartbedByBBSMT() { GM_addStyle( ` #imglist .p_img a{ float: left; height: 36px; } #imglist .del a{ padding: 0; } ` ); $jq("#imglist .up_btn").append($jq("#filedata")); $jq(document).on("click", "#imglist .up_btn a", function () { $jq(this).next().click(); }); $jq(document).on("click", "#imglist .p_img a", function () { let obj = $jq(this); if (obj.attr("onclick") == null) { let img_id = obj.find("img").attr("id").replace("aimg_", ""); comiis_addsmilies(`[attachimg]${img_id}[/attachimg]`); } }); } function chartbedByKggzs() { /* 编辑器图片上传 康哥图床 */ GM_addStyle( ` #imglist_kggzs .delImg{ position: absolute; top: -5px; left: -5px; } ` ); let chartBedUrl = "https://img.kggzs.cn/api/v1"; let chartBedUser = GM_getValue("KggzsChartBedUser"); let chartBedPwd = GM_getValue("KggzsChartBedPwd"); let chartBedToken = null; let code = { 401: "未登录或授权失败", 403: "管理员关闭了接口功能", 429: "超出请求配额,请求受限", 500: "服务端出现异常", }; function getToken() { return new Promise((resolve) => { GM_xmlhttpRequest({ url: `${chartBedUrl}/tokens`, method: "POST", timeout: 5000, data: `email=${chartBedUser}&password=${chartBedPwd}`, headers: { Accept: "application/json", "User-Agent": utils.getRandomPCUA(), "Content-Type": "application/x-www-form-urlencoded", }, onload: (response) => { if (code[response.status] != null) { popups.toast(code[response.status]); resolve(null); return; } let json_data = JSON.parse(response.responseText); if (json_data["status"]) { popups.toast("token成功获取"); resolve(json_data["data"]["token"]); } else { popups.toast(json_data["message"]); resolve(null); } }, onerror: () => { popups.toast("网络异常"); resolve(null); }, ontimeout: () => { popups.toast("请求超时"); resolve(null); }, }); }); } function uploadImage(imageFile) { let res_data = { imageUri: null, json_data: null, }; let form = new FormData(); form.append("strategy_id", 2); /* 存储策略 */ form.append("file", imageFile); return new Promise((resolve) => { GM_xmlhttpRequest({ url: `${chartBedUrl}/upload`, method: "POST", data: form, async: false, headers: { Accept: "application/json", "User-Agent": utils.getRandomPCUA(), Authorization: `Bearer ${chartBedToken}`, }, onload: (response) => { if (code[response.status] != null) { popups.toast(code[response.status]); resolve(res_data); return; } if (response.responseText.match("502 Bad Gateway")) { popups.toast("获取返回结果502失败"); resolve(res_data); return; } let json_data = JSON.parse(response.responseText); console.log(json_data); if (json_data["status"]) { popups.toast("上传成功"); let file_reader = new FileReader(); /* FileReader主要用于将文件内容读入内存,通过一系列异步接口,可以在主线程中访问本地文件 */ file_reader.readAsDataURL( imageFile ); /* 读取图片的内容生成的base64编码的图 */ /* 读取完成后,执行该回调函数,它会返回读取的结果result */ file_reader.onload = function () { let imageUri = this.result; /* 此时的图片已经存储到了result中 */ res_data["imageUri"] = imageUri; res_data["json_data"] = json_data; resolve(res_data); }; } else { console.log(json_data); popups.toast(json_data["message"]); resolve(res_data); } }, onerror: () => { popups.toast("网络异常"); resolve(res_data); }, }); }); } function deleteImage(imageKey) { return new Promise((resolve) => { GM_xmlhttpRequest({ url: `${chartBedUrl}/images/:${imageKey}`, method: "DELETE", async: false, timeout: 5000, data: JSON.stringify({ key: "", }), headers: { Accept: "application/json", "User-Agent": utils.getRandomPCUA(), Authorization: `Bearer ${chartBedToken}`, }, onload: (response) => { if (code[response.status] != null) { popups.toast(code[response.status]); resolve(res_data); return; } let json_data = JSON.parse(response.responseText); console.log(json_data); }, onerror: () => { popups.toast("网络异常"); resolve(res_data); }, ontimeout: () => { popups.toast("请求超时"); resolve(res_data); }, }); }); } function clearData() { chartBedUser = ""; chartBedPwd = ""; chartBedToken = null; GM_deleteValue("KggzsChartBedUser"); GM_deleteValue("KggzsChartBedPwd"); } function checkLogin() { return new Promise(async (resolve) => { if (!chartBedUser || !chartBedPwd) { let loginCallBack = () => { let user = $jq("#chartbed_user").val().trim(); let pwd = $jq("#chartbed_pwd").val().trim(); if (user && pwd) { GM_setValue("KggzsChartBedUser", user); GM_setValue("KggzsChartBedPwd", pwd); chartBedUser = user; chartBedPwd = pwd; popups.closeConfirm(); checkLogin().then((status) => { resolve(status); }); } else { popups.toast("账号或密码不能为空"); } }; mobile.chartBed.popupUserPwd( "康哥图床", "https://img.kggzs.cn/register", loginCallBack ); } else if (chartBedToken == null) { popups.loadingMask(); popups.toast("正在配置token"); chartBedToken = await getToken(); popups.closeMask(); console.log("token:" + chartBedToken); if (chartBedToken != null) { resolve(true); } else { clearData(); resolve(false); } } else { resolve(true); } }); } $jq(document).on( "click", "#imglist_kggzs .up_btn a", async function () { $jq("#filedata_kggzs").val(""); $jq("#filedata_kggzs").click(); } ); $jq(document).on("change", "#filedata_kggzs", async (event) => { let chooseImageFiles = event.currentTarget.files; if (chooseImageFiles.length == 0) { return; } let needUploadImageArray = []; let needUploadImageFileArray = []; let uploadFileAwaitFunction = async (chooseImageFileItemIndex) => { let imageFile = chooseImageFiles[chooseImageFileItemIndex]; console.log("上传图片:", imageFile); let uploadImageReturn = await uploadImage(imageFile); if (uploadImageReturn["json_data"] != null) { console.log(uploadImageReturn); let image_id_encoded = uploadImageReturn["json_data"]["data"]["key"]; let image_url = uploadImageReturn["json_data"]["data"]["links"]["url"]; let image_thumb_url = uploadImageReturn["json_data"]["data"]["links"][ "thumbnail_url" ]; let image_name = uploadImageReturn["json_data"]["data"]["origin_name"]; let image_uri = uploadImageReturn["imageUri"]; let uploadImageHTML = `
  • 插入
  • `; $jq("#imglist_kggzs").append($jq(uploadImageHTML)); mobile.chartBed.storage.add( "kggzs", image_id_encoded, image_url, image_thumb_url, image_name ); } }; let completeFunction = () => { popups.closeMask(); $jq("#filedata_kggzs").val(""); }; let waterMarkAwaitFunction = async () => { popups.loadingMask(); Promise.all( Array.from(chooseImageFiles).map(async (item, index) => { if (item.type === "image/gif") { /* 不支持对GIF添加水印 */ let image_base64 = await utils.parseFileToBase64(item); needUploadImageArray = needUploadImageArray.concat(image_base64); needUploadImageFileArray = needUploadImageFileArray.concat(item); } else { popups.toast( `添加水印 ${index + 1}/${chooseImageFiles.length}` ); var watermark = new Watermark(); await watermark.setFile(item); watermark.addText({ text: [GM_getValue("chartBedWaterMarkText", "MT论坛")], fontSize: GM_getValue("chartBedWaterMarkFontSize"), color: GM_getValue("chartBedWaterMarkFontColor"), globalAlpha: GM_getValue("chartBedWaterGlobalAlpha"), rotateAngle: GM_getValue("chartBedWaterMarkRotationAngle"), xMoveDistance: GM_getValue("chartBedWaterXMoveDistance"), yMoveDistance: GM_getValue("chartBedWaterYMoveDistance"), }); needUploadImageArray = needUploadImageArray.concat( watermark.render("png") ); needUploadImageFileArray = needUploadImageFileArray.concat( utils.parseBase64ToFile( watermark.render("png"), "WaterMark_" + item.name ) ); } }) ).then(async () => { chooseImageFiles = needUploadImageFileArray; popups.closeMask(); if (GM_getValue("chartBedWaterMarkAutoDefault")) { checkLogin().then((loginStatus) => { if (!loginStatus) { return; } popups.loadingMask(); popups.toast("上传水印图片中...请稍后"); console.log(`图片数量:${needUploadImageFileArray.length}`); utils .waitArrayLoopToEnd( needUploadImageFileArray, uploadFileAwaitFunction ) .then(() => { utils.tryCatch().run(completeFunction); }); return null; }); } else { let renderHTML = ""; Array.from(needUploadImageArray).forEach((item) => { renderHTML = renderHTML + ''; }); popups.confirm({ text: `
    ${renderHTML}
    `, mask: true, only: true, ok: { text: "继续上传", callback: async () => { popups.closeConfirm(); checkLogin().then((loginStatus) => { if (!loginStatus) { return; } popups.loadingMask(); popups.toast("上传水印图片中...请稍后"); console.log( `图片数量:${needUploadImageFileArray.length}` ); utils .waitArrayLoopToEnd( needUploadImageFileArray, uploadFileAwaitFunction ) .then(() => { utils.tryCatch().run(completeFunction); }); }); }, }, other: { enable: true, text: "保存至本地", callback: () => { Array.from(needUploadImageFileArray).forEach( async (item, index) => { let base64Image = await utils.parseFileToBase64(item); utils.downloadBase64(item.name, base64Image); } ); }, }, }); } }); }; if (GM_getValue("chartBedAddWaterMark")) { utils.tryCatch().run(waterMarkAwaitFunction); } else { checkLogin().then((loginStatus) => { if (!loginStatus) { return; } popups.loadingMask(); popups.toast("上传图片中...请稍后"); console.log(`图片数量:${chooseImageFiles.length}`); utils .waitArrayLoopToEnd(chooseImageFiles, uploadFileAwaitFunction) .then(() => { utils.tryCatch().run(completeFunction); }); }); } }); $jq(document).on("click", "#imglist_kggzs .delImg", async (event) => { utils.preventEvent(event); event.currentTarget.parentElement.remove(); /* popups.toast('删除中,请稍后'); let id_encoded = e.currentTarget.getAttribute("id-encode"); if(!id_encoded){ popups.toast('获取id_encoded失败,请自行去Hello图床删除'); return; } let deleteStatus = await deleteImage(key); if(deleteStatus){ e.currentTarget.parentElement.remove(); mobile.chartBed.storage.delete("kggzs",id_encoded); } */ }); } function chartbedByHello() { /* 编辑器图片上传Hello图床 */ GM_addStyle( `#imglist_hello .delImg{position:absolute;top:-5px;left:-5px}` ); let chartBedUrl = "https://www.helloimg.com"; let chartBedUser = GM_getValue("HelloChartBedUser"); let chartBedPwd = GM_getValue("HelloChartBedPwd"); let chartBedAuthToken = null; let loginStatus = false; /* 登录状态 */ let clearData = () => { GM_deleteValue("HelloChartBedUser"); GM_deleteValue("HelloChartBedPwd"); loginStatus = false; chartBedUser = ""; chartBedPwd = ""; chartBedAuthToken = null; }; function checkLogin() { return new Promise(async (resolve) => { if (!chartBedUser || !chartBedPwd) { let loginCallBack = () => { let user = $jq("#chartbed_user").val().trim(); let pwd = $jq("#chartbed_pwd").val().trim(); if (user && pwd) { GM_setValue("HelloChartBedUser", user); GM_setValue("HelloChartBedPwd", pwd); chartBedUser = user; chartBedPwd = pwd; popups.closeConfirm(); checkLogin().then((status) => { resolve(status); }); } else { popups.toast("账号或密码不能为空"); } }; mobile.chartBed.popupUserPwd( "Hello图床", "https://www.helloimg.com/signup", loginCallBack ); } else if (chartBedAuthToken == null && !loginStatus) { popups.loadingMask(); popups.toast("正在配置auth_token"); chartBedAuthToken = await mobile.chartBed.getAuthToken( chartBedUrl ); console.log("auth_token:", chartBedAuthToken); if (chartBedAuthToken != null) { popups.toast("正在登录Hello图床"); let retloginStatus = await mobile.chartBed.login( chartBedUrl, chartBedUser, chartBedPwd, chartBedAuthToken ); popups.closeMask(); if (retloginStatus) { loginStatus = true; resolve(true); return; } else { clearData(); resolve(false); return; } } popups.closeMask(); resolve(false); } else { resolve(true); } }); } $jq(document).on( "click", "#imglist_hello .up_btn a", async function () { $jq("#filedata_hello").val(""); $jq("#filedata_hello").click(); } ); $jq(document).on("change", "#filedata_hello", async (event) => { let chooseImageFiles = event.currentTarget.files; if (chooseImageFiles.length == 0) { return; } let needUploadImageArray = []; let needUploadImageFileArray = []; let uploadFileAwaitFunction = async (chooseImageFileItemIndex) => { let imageFile = chooseImageFiles[chooseImageFileItemIndex]; console.log("上传图片:", imageFile); let uploadImageReturn = await mobile.chartBed.uploadImage( chartBedUrl, chartBedAuthToken, imageFile ); if (uploadImageReturn["json_data"] != null) { let image_id_encoded = uploadImageReturn["json_data"]["image"]["id_encoded"]; let image_url = uploadImageReturn["json_data"]["image"]["url"]; let image_thumb_url = uploadImageReturn["json_data"]["image"]["thumb"]["url"]; let image_name = uploadImageReturn["json_data"]["image"]["filename"]; let image_uri = uploadImageReturn["imageUri"]; let uploadImageHTML = `
  • 插入
  • `; $jq("#imglist_hello").append($jq(uploadImageHTML)); mobile.chartBed.storage.add( "hello", image_id_encoded, image_url, image_thumb_url, image_name ); } }; let completeFunction = () => { popups.closeMask(); $jq("#filedata_hello").val(""); }; let waterMarkAwaitFunction = async () => { popups.loadingMask(); Promise.all( Array.from(chooseImageFiles).map(async (item, index) => { if (item.type === "image/gif") { /* 不支持对GIF添加水印 */ let image_base64 = await utils.parseFileToBase64(item); needUploadImageArray = needUploadImageArray.concat(image_base64); needUploadImageFileArray = needUploadImageFileArray.concat(item); } else { popups.toast( `添加水印 ${index + 1}/${chooseImageFiles.length}` ); var watermark = new Watermark(); await watermark.setFile(item); watermark.addText({ text: [GM_getValue("chartBedWaterMarkText", "MT论坛")], fontSize: GM_getValue("chartBedWaterMarkFontSize"), color: GM_getValue("chartBedWaterMarkFontColor"), globalAlpha: GM_getValue("chartBedWaterGlobalAlpha"), rotateAngle: GM_getValue("chartBedWaterMarkRotationAngle"), xMoveDistance: GM_getValue("chartBedWaterXMoveDistance"), yMoveDistance: GM_getValue("chartBedWaterYMoveDistance"), }); needUploadImageArray = needUploadImageArray.concat( watermark.render("png") ); needUploadImageFileArray = needUploadImageFileArray.concat( utils.parseBase64ToFile( watermark.render("png"), "WaterMark_" + item.name ) ); } }) ).then(async () => { chooseImageFiles = needUploadImageFileArray; popups.closeMask(); if (GM_getValue("chartBedWaterMarkAutoDefault", false)) { checkLogin().then((loginStatus) => { if (!loginStatus) { return; } popups.loadingMask(); popups.toast("上传水印图片中...请稍后"); console.log(`图片数量:${needUploadImageFileArray.length}`); utils .waitArrayLoopToEnd( needUploadImageFileArray, uploadFileAwaitFunction ) .then(() => { utils.tryCatch().run(completeFunction); }); }); } else { let renderHTML = ""; Array.from(needUploadImageArray).forEach((item) => { renderHTML = renderHTML + ''; }); popups.confirm({ text: `
    ${renderHTML}
    `, mask: true, only: true, ok: { text: "继续上传", callback: async () => { popups.closeConfirm(); checkLogin().then((loginStatus) => { if (loginStatus) { popups.loadingMask(); popups.toast("上传水印图片中...请稍后"); console.log( `图片数量:${needUploadImageFileArray.length}` ); utils .waitArrayLoopToEnd( needUploadImageFileArray, uploadFileAwaitFunction ) .then(() => { utils.tryCatch().run(completeFunction); }); } else { console.log("登录失败"); } }); }, }, other: { enable: true, text: "保存至本地", callback: () => { Array.from(needUploadImageFileArray).forEach( async (item, index) => { let base64Image = await utils.parseFileToBase64(item); utils.downloadBase64(item.name, base64Image); } ); }, }, }); } }); }; if (GM_getValue("chartBedAddWaterMark", false)) { utils.tryCatch().run(waterMarkAwaitFunction); } else { checkLogin().then((loginStatus) => { if (!loginStatus) { return; } popups.loadingMask(); popups.toast("上传图片中...请稍后"); console.log(`图片数量:${chooseImageFiles.length}`); utils .waitArrayLoopToEnd(chooseImageFiles, uploadFileAwaitFunction) .then(() => { utils.tryCatch().run(completeFunction); }); }); } }); $jq(document).on( "click", "#imglist_hello .delImg", async function (event) { utils.preventEvent(event); popups.loadingMask(); popups.toast("删除中,请稍后"); let id_encoded = event.currentTarget.getAttribute("id-encode"); if (!id_encoded) { popups.closeMask(); popups.toast("获取id_encoded失败,请自行去Hello图床删除"); return; } let deleteStatus = await mobile.chartBed.deleteImage( chartBedUrl, chartBedAuthToken, id_encoded ); popups.closeMask(); if (deleteStatus) { $jq(this).parent().remove(); mobile.chartBed.storage.delete("hello", id_encoded); } } ); } function chartbedByZ4a() { /* 编辑器图片上传z4a图床 */ GM_addStyle( `#imglist_z4a .delImg{position:absolute;top:-5px;left:-5px}` ); let chartBedUrl = "https://www.z4a.net"; let chartBedUser = GM_getValue("Z4AChartBedUser"); let chartBedPwd = GM_getValue("Z4AChartBedPwd"); let chartBedAuthToken = null; let loginStatus = false; /* 登录状态 */ let clearData = () => { GM_deleteValue("Z4AChartBedUser"); GM_deleteValue("Z4AChartBedPwd"); loginStatus = false; chartBedUser = ""; chartBedPwd = ""; chartBedAuthToken = null; }; function checkLogin() { return new Promise(async (resolve) => { if (!chartBedUser || !chartBedPwd) { let loginCallBack = () => { let user = $jq("#chartbed_user").val().trim(); let pwd = $jq("#chartbed_pwd").val().trim(); if (user && pwd) { GM_setValue("Z4AChartBedUser", user); GM_setValue("Z4AChartBedPwd", pwd); chartBedUser = user; chartBedPwd = pwd; popups.closeConfirm(); checkLogin().then((status) => { resolve(status); }); } else { popups.toast("账号或密码不能为空"); } }; mobile.chartBed.popupUserPwd( "Z4A图床", "https://www.z4a.net/signup", loginCallBack ); } else if (chartBedAuthToken == null && !loginStatus) { popups.loadingMask(); popups.toast("正在配置auth_token"); chartBedAuthToken = await mobile.chartBed.getAuthToken( chartBedUrl ); console.log("auth_token:", chartBedAuthToken); if (chartBedAuthToken != null) { popups.toast("正在登录Z4A图床"); let retloginStatus = await mobile.chartBed.login( chartBedUrl, chartBedUser, chartBedPwd, chartBedAuthToken ); popups.closeMask(); if (retloginStatus) { console.log("登录成功"); loginStatus = true; resolve(true); return; } else { clearData(); resolve(false); return; } } popups.closeMask(); resolve(false); } else { resolve(true); } }); } $jq(document).on("click", "#imglist_z4a .up_btn a", async function () { $jq("#filedata_z4a").val(""); $jq("#filedata_z4a").click(); }); $jq(document).on("change", "#filedata_z4a", async (event) => { let chooseImageFiles = event.currentTarget.files; if (chooseImageFiles.length == 0) { return; } let needUploadImageArray = []; let needUploadImageFileArray = []; let uploadFileAwaitFunction = async (chooseImageFileItemIndex) => { let imageFile = chooseImageFiles[chooseImageFileItemIndex]; console.log("上传图片:", imageFile); let uploadImageReturn = await mobile.chartBed.uploadImage( chartBedUrl, chartBedAuthToken, imageFile ); if (uploadImageReturn["json_data"] != null) { let image_id_encoded = uploadImageReturn["json_data"]["image"]["id_encoded"]; let image_url = uploadImageReturn["json_data"]["image"]["url"]; let image_thumb_url = uploadImageReturn["json_data"]["image"]["thumb"]["url"]; let image_name = uploadImageReturn["json_data"]["image"]["filename"]; let image_uri = uploadImageReturn["imageUri"]; let uploadImageHTML = `
  • 插入
  • `; $jq("#imglist_z4a").append($jq(uploadImageHTML)); mobile.chartBed.storage.add( "z4a", image_id_encoded, image_url, image_thumb_url, image_name ); } }; let completeFunction = () => { popups.closeMask(); $jq("#filedata_z4a").val(""); }; let waterMarkAwaitFunction = async () => { popups.loadingMask(); Promise.all( Array.from(chooseImageFiles).map(async (item, index) => { if (item.type === "image/gif") { /* 不支持对GIF添加水印 */ let image_base64 = await utils.parseFileToBase64(item); needUploadImageArray = needUploadImageArray.concat(image_base64); needUploadImageFileArray = needUploadImageFileArray.concat(item); } else { popups.toast( `添加水印 ${index + 1}/${chooseImageFiles.length}` ); var watermark = new Watermark(); await watermark.setFile(item); watermark.addText({ text: [GM_getValue("chartBedWaterMarkText", "MT论坛")], fontSize: GM_getValue("chartBedWaterMarkFontSize"), color: GM_getValue("chartBedWaterMarkFontColor"), globalAlpha: GM_getValue("chartBedWaterGlobalAlpha"), rotateAngle: GM_getValue("chartBedWaterMarkRotationAngle"), xMoveDistance: GM_getValue("chartBedWaterXMoveDistance"), yMoveDistance: GM_getValue("chartBedWaterYMoveDistance"), }); needUploadImageArray = needUploadImageArray.concat( watermark.render("png") ); needUploadImageFileArray = needUploadImageFileArray.concat( utils.parseBase64ToFile( watermark.render("png"), "WaterMark_" + item.name ) ); } }) ).then(async () => { chooseImageFiles = needUploadImageFileArray; popups.closeMask(); if (GM_getValue("chartBedWaterMarkAutoDefault")) { checkLogin().then((loginStatus) => { if (!loginStatus) { return; } popups.loadingMask(); popups.toast("上传水印图片中...请稍后"); console.log(`图片数量:${needUploadImageFileArray.length}`); utils .waitArrayLoopToEnd( needUploadImageFileArray, uploadFileAwaitFunction ) .then(() => { utils.tryCatch().run(completeFunction); }); }); } else { let renderHTML = ""; Array.from(needUploadImageArray).forEach((item) => { renderHTML = renderHTML + ''; }); popups.confirm({ text: `
    ${renderHTML}
    `, mask: true, only: true, ok: { text: "继续上传", callback: async () => { popups.closeConfirm(); let login_status = await checkLogin(); if (login_status) { popups.loadingMask(); popups.toast("上传水印图片中...请稍后"); console.log( `图片数量:${needUploadImageFileArray.length}` ); utils .waitArrayLoopToEnd( needUploadImageFileArray, uploadFileAwaitFunction ) .then(() => { utils.tryCatch().run(completeFunction); }); } }, }, other: { enable: true, text: "保存至本地", callback: () => { Array.from(needUploadImageFileArray).forEach( async (item, index) => { let base64Image = await utils.parseFileToBase64(item); utils.downloadBase64(item.name, base64Image); } ); }, }, }); } }); }; if (GM_getValue("chartBedAddWaterMark")) { utils.tryCatch().run(waterMarkAwaitFunction); } else { checkLogin().then((loginStatus) => { if (!loginStatus) { return; } popups.loadingMask(); popups.toast("上传图片中...请稍后"); console.log(`图片数量:${chooseImageFiles.length}`); utils .waitArrayLoopToEnd(chooseImageFiles, uploadFileAwaitFunction) .then(() => { utils.tryCatch().run(completeFunction); }); }); } }); $jq(document).on( "click", "#imglist_z4a .delImg", async function (event) { utils.preventEvent(event); popups.loadingMask(); popups.toast("删除中,请稍后"); let id_encoded = event.currentTarget.getAttribute("id-encode"); if (!id_encoded) { popups.closeMask(); popups.toast("获取id_encoded失败,请自行去Z4A图床删除"); return; } let deleteStatus = await mobile.chartBed.deleteImage( chartBedUrl, chartBedAuthToken, id_encoded ); popups.closeMask(); if (deleteStatus) { $jq(this).parent().remove(); mobile.chartBed.storage.delete("z4a", id_encoded); } } ); } function chartbedByMT() { /* MT图床(限制了referer) */ $jq(document).on("click", "#imglist_mt .up_btn a", async function () { /* 点击上传图标 */ $jq("#filedata_mt").val(""); $jq("#filedata_mt").click(); }); $jq(document).on("change", "#filedata_mt", async (event) => { /* 监听file控件内数据改变 */ let chooseImageFiles = event.currentTarget.files; if (chooseImageFiles.length == 0) { return; } let needUploadImageArray = []; let needUploadImageFileArray = []; /** * 获取MT图床的CSRF参数 * @returns {Promise} */ function getCSRFToken() { return new Promise((resolve) => { GM_xmlhttpRequest({ url: "https://img.binmt.cc/", method: "GET", async: false, timeout: 5000, headers: { "User-Agent": utils.getRandomPCUA(), Referer: "https://img.binmt.cc/", Origin: "https://img.binmt.cc", }, onload: (response) => { console.log(response); let respDoc = utils.parseFromString(response.responseText); let metaCSRFToken = respDoc .querySelector('meta[name="csrf-token"]') ?.getAttribute("content"); console.log("获取的CSRF token:", metaCSRFToken); resolve(metaCSRFToken || null); }, onerror: (response) => { console.log(response); popups.toast("网络异常"); resolve(null); }, ontimeout: () => { popups.toast("请求超时"); resolve(null); }, }); }); } /** * 上传图片 * @param {string} csrfToken * @param {File} imageFile * @returns {Promise} */ function uploadImage(csrfToken, imageFile) { let resultData = { imageUri: null, json_data: null, }; let form = new FormData(); form.append("strategy_id", 2); /* 存储策略 */ form.append("file", imageFile); return new Promise((resolve) => { GM_xmlhttpRequest({ url: `https://img.binmt.cc/upload`, method: "POST", data: form, async: false, headers: { Accept: "application/json, text/javascript, */*; q=0.01", "User-Agent": utils.getRandomAndroidUA(), Origin: "https://img.binmt.cc", pragma: "no-cache", "Accept-Encoding": "gzip, deflate, br", "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6", referer: "https://img.binmt.cc/", Pragma: "no-cache", "x-csrf-token": csrfToken, "X-Requested-With": "XMLHttpRequest", }, onload: (response) => { let json_data = JSON.parse(response.responseText); console.log(json_data); if (json_data["status"]) { popups.toast("上传成功"); let file_reader = new FileReader(); /* FileReader主要用于将文件内容读入内存,通过一系列异步接口,可以在主线程中访问本地文件 */ file_reader.readAsDataURL( imageFile ); /* 读取图片的内容生成的base64编码的图 */ /* 读取完成后,执行该回调函数,它会返回读取的结果result */ file_reader.onload = function () { let imageUri = this.result; /* 此时的图片已经存储到了result中 */ resultData["imageUri"] = imageUri; resultData["json_data"] = json_data; resolve(resultData); }; } else { console.log(json_data); popups.toast(json_data["message"]); resolve(resultData); } }, onerror: (response) => { console.log(response); popups.toast("网络异常"); resolve(resultData); }, }); }); } function completeFunction() { popups.closeMask(); $jq("#filedata_mt").val(""); } async function uploadFileAwaitFunction(chooseImageFileItemIndex) { let imageFile = chooseImageFiles[chooseImageFileItemIndex]; console.log("上传图片:", imageFile); let csrfToken = await getCSRFToken(); if (csrfToken == null) { popups.toast({ text: "获取CSRF Token失败", }); return; } let uploadImageReturn = await uploadImage(csrfToken, imageFile); if (uploadImageReturn["json_data"] != null) { let image_id_encoded = uploadImageReturn["json_data"]["data"]["id"]; /* 图片id */ let image_url = uploadImageReturn["json_data"]["data"]["links"][ "url" ]; /* 图片url */ let image_thumb_url = uploadImageReturn["json_data"]["data"]["links"][ "thumbnail_url" ]; /* 图片缩略图 */ let image_name = uploadImageReturn["json_data"]["data"][ "origin_name" ]; /* 图片文件名 */ let image_uri = uploadImageReturn["imageUri"]; /* 图片base64编码数据 */ let uploadImageHTML = `
  • 插入
  • `; $jq("#imglist_mt").append($jq(uploadImageHTML)); mobile.chartBed.storage.add( "mt", image_id_encoded, image_url, image_thumb_url, image_name ); } } async function waterMarkAwaitFunction() { popups.loadingMask(); Promise.all( Array.from(chooseImageFiles).map(async (item, index) => { if (item.type === "image/gif") { /* 不支持对GIF添加水印 */ let image_base64 = await utils.parseFileToBase64(item); needUploadImageArray = needUploadImageArray.concat(image_base64); needUploadImageFileArray = needUploadImageFileArray.concat(item); } else { popups.toast( `添加水印 ${index + 1}/${chooseImageFiles.length}` ); var watermark = new Watermark(); await watermark.setFile(item); watermark.addText({ text: [GM_getValue("chartBedWaterMarkText", "MT论坛")], fontSize: GM_getValue("chartBedWaterMarkFontSize"), color: GM_getValue("chartBedWaterMarkFontColor"), globalAlpha: GM_getValue("chartBedWaterGlobalAlpha"), rotateAngle: GM_getValue("chartBedWaterMarkRotationAngle"), xMoveDistance: GM_getValue("chartBedWaterXMoveDistance"), yMoveDistance: GM_getValue("chartBedWaterYMoveDistance"), }); needUploadImageArray = needUploadImageArray.concat( watermark.render("png") ); needUploadImageFileArray = needUploadImageFileArray.concat( utils.parseBase64ToFile( watermark.render("png"), "WaterMark_" + item.name ) ); } }) ).then(async () => { chooseImageFiles = needUploadImageFileArray; popups.closeMask(); if (GM_getValue("chartBedWaterMarkAutoDefault")) { popups.loadingMask(); popups.toast("上传水印图片中...请稍后"); console.log(`图片数量:${needUploadImageFileArray.length}`); utils .waitArrayLoopToEnd( needUploadImageFileArray, uploadFileAwaitFunction ) .then(() => { utils.tryCatch().run(completeFunction); }); return null; } let renderHTML = ""; Array.from(needUploadImageArray).forEach((item) => { renderHTML = renderHTML + ''; }); popups.confirm({ text: `
    ${renderHTML}
    `, mask: true, only: true, ok: { text: "继续上传", callback: async () => { popups.closeConfirm(); popups.loadingMask(); popups.toast("上传水印图片中...请稍后"); console.log(`图片数量:${needUploadImageFileArray.length}`); utils .waitArrayLoopToEnd( needUploadImageFileArray, uploadFileAwaitFunction ) .then(() => { utils.tryCatch().run(completeFunction); }); }, }, other: { enable: true, text: "保存至本地", callback: () => { Array.from(needUploadImageFileArray).forEach( async (item, index) => { let base64Image = await utils.parseFileToBase64(item); utils.downloadBase64(item.name, base64Image); } ); }, }, }); }); } if (GM_getValue("chartBedAddWaterMark")) { utils.tryCatch().run(waterMarkAwaitFunction); } else { popups.loadingMask(); popups.toast("上传图片中...请稍后"); console.log(`图片数量:${chooseImageFiles.length}`); utils .waitArrayLoopToEnd(chooseImageFiles, uploadFileAwaitFunction) .then(() => { utils.tryCatch().run(completeFunction); }); } }); $jq(document).on( "click", "#imglist_mt .delImg", async function (event) { /* 删除上传的图片-目前无法删除 */ utils.preventEvent(event); const id_encoded = $jq(this).attr("id-encode"); $jq(this).parent().remove(); mobile.chartBed.storage.delete("mt", id_encoded); } ); } function chartbedByHistory() { /* 所有图床历史上传过的图片 */ GM_addStyle( `.comiis_post_imglist li .delImg{position:absolute;top:-5px;left:-5px}` ); $jq(document).on( "click", "li[id*='comiis_pictitle_tab_n_'][data-history]", function () { if (GM_getValue("chartBedsImagesHistory") == undefined) { GM_setValue("chartBedsImagesHistory", []); } let historyImages = mobile.chartBed.storage.get(); if (historyImages == []) { return; } let isAddHistoryImages = $jq("#imglist_history").children(); if (isAddHistoryImages.length === historyImages.length) { /* 没有新图片 */ console.log("没有新图片"); return; } else if (isAddHistoryImages.length === 0) { /* 无图片-全部加进去 */ console.log("无图片-全部加进去"); $jq.each(historyImages, (i) => { let _id = historyImages[i]["id_encoded"]; let _web = historyImages[i]["web"]; let _url = historyImages[i]["url"]; let _thumb_url = historyImages[i]["thumb_url"]; let _name = historyImages[i]["name"]; let _imageHTML = `
  • ${_web}
  • `; $jq("#imglist_history").append($jq(_imageHTML)); }); } else if (isAddHistoryImages.length < historyImages.length) { /* 其它地方增加了数据-更新结构 */ console.log("其它地方增加了数据-更新结构"); var needAddData = utils.uniqueArray( historyImages, isAddHistoryImages, (item, item2) => { let obj = $jq(item2); let spanElement = obj.find("span.delImg"); let _id = spanElement.attr("t-id"); let _web = spanElement.attr("t-web"); if (!isNaN(parseInt(_id))) { _id = parseInt(_id); } return item["web"] === _web && item["id_encoded"] === _id ? true : false; } ); console.log("新增数组:", needAddData); Array.from(needAddData).forEach((item, index) => { let _id = item["id_encoded"]; let _web = item["web"]; let _url = item["url"]; let _thumb_url = item["thumb_url"]; let _name = item["name"]; let _imageHTML = `
  • ${_web}
  • `; $jq("#imglist_history").append($jq(_imageHTML)); }); } else if (isAddHistoryImages.length > historyImages.length) { /* 其它地方删除了数据,更新结构 */ console.log("其它地方删除了数据,更新结构"); var needRemoveData = utils.uniqueArray( isAddHistoryImages, historyImages, (item, item2) => { let obj = $jq(item); let spanElement = obj.find("span.delImg"); let _id = spanElement.attr("t-id"); let _web = spanElement.attr("t-web"); if (!isNaN(parseInt(_id))) { _id = parseInt(_id); } return item2["web"] === _web && item2["id_encoded"] === _id ? true : false; } ); console.log("需去除的数组:", needRemoveData); needRemoveData.forEach((item) => { item.remove(); }); } } ); $jq(document).on("click", "#imglist_history .delImg", function (event) { utils.preventEvent(event); let obj = $jq(this); let _t_web = obj.attr("t-web"); let _t_id = obj.attr("t-id"); console.log(_t_web, _t_id); let deleteStatus = mobile.chartBed.storage.delete(_t_web, _t_id); if (deleteStatus) { obj.parent()?.remove(); } }); } let imgBtn = `图片`; let menu = ` `; GM_addStyle(` #filedata,#filedata_hello,#filedata_kggzs,#filedata_z4a{display:none} .comiis_tip dt p{padding:10px 0} .upload-image-water{overflow-y:auto} .upload-image-water img{width:100%;margin:10px 0}`); let jqMenu = $jq(menu); jqMenu .find(".comiis_upbox.comiis_allowpostimg") .append( $jq( ".comiis_wzpost.comiis_input_style .comiis_upbox.comiis_allowpostimg" ).children() ); $jq(".swiper-wrapper.comiis_post_ico").append(imgBtn); $jq("#comiis_post_tab").append(jqMenu); utils.tryCatch().run(chartbedByBBSMT); utils.tryCatch().run(chartbedByKggzs); utils.tryCatch().run(chartbedByHello); utils.tryCatch().run(chartbedByZ4a); utils.tryCatch().run(chartbedByMT); utils.tryCatch().run(chartbedByHistory); }, /** * 编辑器优化-简略 */ editorOptimization() { if (!DOM_CONFIG.methodRunCheck([DOM_CONFIG.urlRegexp.forumPost], "v49")) { return; } GM_addStyle(` #comiis_foot_menu_beautify{position:fixed;display:inline-flex;z-index:90;left:0;right:0;bottom:0;width:100%;height:48px;overflow:hidden;align-content:center;justify-content:center;align-items:center} #comiis_foot_menu_beautify_big{position:fixed;display:inline-flex;flex-direction:column;z-index:92;left:0;right:0;bottom:0;width:100%;min-height:120px;overflow:hidden;align-content:center;justify-content:center;align-items:center} #comiis_foot_menu_beautify input.bg_e.f_c::-webkit-input-placeholder{padding-left:10px;color:#999} #comiis_foot_menu_beautify input.bg_e.f_c::-moz-input-placeholder{padding-left:10px;color:#999} #comiis_foot_menu_beautify .reply_area ul li a{display:block;width:22px;height:22px;padding:4px 8px;margin:8px 0;position:relative} #comiis_foot_menu_beautify .reply_area ul{display:inline-flex;align-content:center;align-items:center;justify-content:center} #comiis_foot_menu_beautify .reply_area,#comiis_foot_menu_beautify .reply_area ul{width:100%} #comiis_foot_menu_beautify .reply_area li a i{width:22px;height:22px;line-height:22px;font-size:22px} #comiis_foot_menu_beautify .reply_area li a span{position:absolute;display:block;font-size:10px;height:14px;line-height:14px;padding:0 6px;right:-8px;top:4px;overflow:hidden;border-radius:20px} #comiis_foot_menu_beautify li[data-attr="回帖"] input{border:transparent;border-radius:15px;height:30px;width:100%} #comiis_foot_menu_beautify_big .comiis_smiley_box{padding:6px 6px 0} #comiis_foot_menu_beautify_big .reply_area{margin:10px 0 5px 0} #comiis_foot_menu_beautify_big .reply_area ul{display:inline-flex;align-content:center;justify-content:center;align-items:flex-end} #comiis_foot_menu_beautify_big li[data-attr="回帖"]{width:75vw;margin-right:15px} #comiis_foot_menu_beautify_big .reply_user_content{width:75vw;word-wrap:break-word;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;margin:8px 10px} #comiis_foot_menu_beautify_big li[data-attr="发表"] .fastpostform_new{text-align:center;margin-bottom:28px} #comiis_foot_menu_beautify_big li[data-attr="发表"] .fastpostform_new i{font-size:22px} #comiis_foot_menu_beautify_big li[data-attr="发表"] input{width:60px;height:30px;border:transparent;color:#fff;background:#d1c9fc;border-radius:30px;margin-bottom:6px} #comiis_foot_menu_beautify_big li[data-attr="发表"] input[data-text=true]{background:#7a61fb} #comiis_foot_menu_beautify_big li[data-attr="回帖"] textarea{padding:10px 10px 10px 10px;border:transparent;border-radius:6px;min-height:70px;max-height:180px;background:#e9e8ec;overflow-y:auto;width:-webkit-fill-available;width:-moz-available} #comiis_foot_menu_beautify .reply_area li[data-attr="回帖"]{width:65%;margin:0 3%;text-align:center} #comiis_foot_menu_beautify .reply_area li:not(first-child){width:7%;text-align:-webkit-center;text-align:center} #comiis_foot_menu_beautify_big .other_area{width:100%;text-align:center} #comiis_foot_menu_beautify_big .other_area .menu_icon a{margin:0 20px} #comiis_foot_menu_beautify_big .other_area i{font-size:24px} #comiis_foot_menu_beautify_big .other_area #comiis_insert_ubb_tab i{font-size:16px} #comiis_foot_menu_beautify_big .other_area .menu_body{background:#f4f4f4} #comiis_foot_menu_beautify_big .other_area .menu_body .comiis_smiley_box .comiis_optimization{max-height:140px;overflow-y:auto;flex-direction:column} #comiis_foot_menu_beautify_big .other_area .menu_body .comiis_smiley_box .bqbox_t{background:#fff} #comiis_foot_menu_beautify_big .other_area .menu_body .comiis_smiley_box .bqbox_t ul#comiis_smilies_key li a.bg_f.b_l.b_r{background:#f4f4f4!important} #comiis_foot_menu_beautify_big .menu_body #comiis_pictitle_tab #comiis_pictitle_key{display:-webkit-box;top:0;left:0;height:42px;line-height:42px;overflow:hidden;overflow-x:auto} #comiis_foot_menu_beautify_big .menu_body #comiis_pictitle_tab #comiis_pictitle_key li{padding:0 10px} #comiis_foot_menu_beautify_big .menu_body #comiis_insert_ubb_tab .comiis_input_style,#comiis_foot_menu_beautify_big .menu_body #comiis_pictitle_tab .comiis_upbox{height:140px;overflow-y:auto;flex-direction:column} #comiis_foot_menu_beautify_big .menu_body #comiis_pictitle_tab #filedata_hello,#comiis_foot_menu_beautify_big .menu_body #comiis_pictitle_tab #filedata_kggzs,#comiis_foot_menu_beautify_big .menu_body #comiis_pictitle_tab #filedata_mt,#comiis_foot_menu_beautify_big .menu_body #comiis_pictitle_tab #filedata_z4a{display:none} @media screen and (max-width:350px){.comiis_bqbox .bqbox_c li{width:14.5%} } @media screen and (min-width:350px) and (max-width:400px){.comiis_bqbox .bqbox_c li{width:12.5%} } @media screen and (min-width:400px) and (max-width:450px){.comiis_bqbox .bqbox_c li{width:11%} } @media screen and (min-width:450px) and (max-width:500px){.comiis_bqbox .bqbox_c li{width:10%} } @media screen and (min-width:500px) and (max-width:550px){.comiis_bqbox .bqbox_c li{width:9.5%} } @media screen and (min-width:550px) and (max-width:600px){.comiis_bqbox .bqbox_c li{width:9%} } @media screen and (min-width:600px) and (max-width:650px){.comiis_bqbox .bqbox_c li{width:8.5%} } @media screen and (min-width:650px) and (max-width:700px){.comiis_bqbox .bqbox_c li{width:8%} } @media screen and (min-width:700px) and (max-width:750px){.comiis_bqbox .bqbox_c li{width:7.5%} } @media screen and (min-width:750px) and (max-width:800px){.comiis_bqbox .bqbox_c li{width:7%} } @media screen and (min-width:800px) and (max-width:850px){.comiis_bqbox .bqbox_c li{width:6.5%} } @media screen and (min-width:850px) and (max-width:1200px){.comiis_bqbox .bqbox_c li{width:6%} } @media screen and (min-width:1200px){.comiis_bqbox .bqbox_c li{width:4.5%} } #imglist_settings button{font-size:13.333px;color:#9baacf;outline:0;border:none;height:35px;width:80px;border-radius:10px;box-shadow:.3rem .3rem .6rem #c8d0e7,-.2rem -.2rem .5rem #fff;font-weight:800;line-height:40px;background:#efefef;padding:0;display:flex;align-items:center;justify-content:center} #imglist_settings button:active{box-shadow:inset .2rem .2rem .5rem #c8d0e7,inset -.2rem -.2rem .5rem #fff!important;color:#638ffb!important}`); let db = new utils.indexedDB("mt_reply_record", "input_text"); let pl = $jq("#comiis_foot_memu .comiis_flex li")[1]; let dz = $jq("#comiis_foot_memu .comiis_flex li")[2]; let sc = $jq("#comiis_foot_memu .comiis_flex li")[3]; let forum_action = $jq("#fastpostform").attr("action"); let forum_serialize = $jq("#fastpostform").serialize(); let forum_url = $jq("#fastpostform .header_y a").attr("href"); $jq("#needmessage[name='message']").remove(); $jq("#imglist").remove(); $jq("#fastpostsubmitline").remove(); $jq("#fastpostsubmit").remove(); $jq("#comiis_foot_memu").hide(); $jq("#comiis_foot_memu").after( $jq(`
    • ${pl.innerHTML}
    • ${dz.innerHTML}
    • ${sc.innerHTML}
    `, timestamp: item["expirationTimeStamp"], }; if (new Date().getTime() > item["expirationTimeStamp"]) { /* 可白嫖 */ if (leftRedBtn != "") { isFreeNotVisitedContentList = [ ...isFreeNotVisitedContentList, concatList, ]; } else { isFreeContentList = [...isFreeContentList, concatList]; } } else { isPaidContentList = [...isPaidContentList, concatList]; } }); console.log("可白嫖但未访问:", isFreeNotVisitedContentList); console.log("可白嫖:", isFreeContentList); console.log("未到白嫖时间:", isPaidContentList); utils.sortListByProperty( isFreeNotVisitedContentList, "expirationTimeStamp", false ); utils.sortListByProperty(isFreeContentList, "timestamp", false); utils.sortListByProperty(isPaidContentList, "timestamp", false); console.log("排序后——可白嫖但未访问:", isFreeNotVisitedContentList); console.log("排序后——可白嫖:", isFreeContentList); console.log("排序后——未到白嫖时间:", isPaidContentList); isFreeContent = utils.mergeArrayToString(isFreeNotVisitedContentList, "content") + utils.mergeArrayToString(isFreeContentList, "content"); isPaidContent = utils.mergeArrayToString( isPaidContentList, "content" ); if (notVisitedNums > 0) { notVisitedTipContent = ` ${notVisitedNums}`; } let dialogIsFreeContent = '
    可白嫖' + notVisitedTipContent + '
    ${leftRedBtn}
    ${item["title"]}
  • ${item["expirationTime"]}
  • ' + isFreeContent + "
    "; let dialogIsPaidContent = '
    需付费' + isPaidContent + "
    "; $jq(".msgcon").html(""); $jq(".msgcon").append(dialogIsFreeContent); $jq(".msgcon").append(dialogIsPaidContent); $jq(".msgcon").css("height", "400px"); $jq(".delsubjecttip i.comiis_font").on("click", (event) => { var t_index = event.target.parentElement.getAttribute("t-index"); popups.confirm({ text: "

    确定移出付费主题白嫖列表?

    ", mask: true, ok: { callback: () => { data.splice(t_index, 1); console.log(data); paymentSubjectReminderHome.setData(data); utils.deleteParentNode(event.target, "tr"); popups.closeConfirm(); }, }, only: true, }); }); $jq("#paymentSubjectReminderIsFreeList").on("click", "a", (event) => { var tIndex = event.target.getAttribute("t-index"); var tHref = event.target.getAttribute("t-href"); console.log(tIndex, tHref); data[tIndex]["isVisited"] = true; paymentSubjectReminderHome.setData(data); window.open(tHref, "_blank"); event.target.setAttribute("style", "color: #000000;"); if ( event.target.parentElement.parentElement.children[0].className != "icon_msgs bg_del" ) { return; } event.target.parentElement.parentElement.children[0].remove(); $jq("#paymentSubjectReminderIsFreeList").append( event.target.parentElement.parentElement.parentElement .parentElement.parentElement ); let notVisitedNums = $jq( ".subjectcanvisit summary span.icon_msgs.bg_del.f_f" ).text(); notVisitedNums = parseInt(notVisitedNums) - 1; if (notVisitedNums > 0) { $jq(".subjectcanvisit summary span.icon_msgs.bg_del.f_f").html( notVisitedNums ); } else { $jq( ".subjectcanvisit summary span.icon_msgs.bg_del.f_f" ).remove(); } }); $jq("#paymentSubjectReminderIsPaidList").on("click", "a", (event) => { var t_index = event.target.getAttribute("t-index"); var t_href = event.target.getAttribute("t-href"); console.log(t_index, t_href); window.open(t_href, "_blank"); event.target.setAttribute("style", "color: #000000;"); }); }, }; if (storageMatchStatus && urlForumPostMatchStatus) { /* 帖子内部-添加进提醒的按钮或者已添加进提醒的按钮点击移出 */ let paySubjectTip = $jq("span.kmren"); /* 购买主题的元素 */ if (paySubjectTip.length != 0) { console.log("当前帖子存在需要购买主题"); let isAddTip = false; let tipBtnHTML = ""; Array.from(setTipForumPostList).forEach((item, index) => { if (window.location.href.match(item["url"])) { isAddTip = true; return; } }); if (isAddTip) { console.log("已设置提醒"); tipBtnHTML = $jq( `` ); tipBtnHTML.on("click", function () { popups.confirm({ text: "

    确定移出付费主题白嫖列表?

    ", ok: { callback: function () { let isRemove = false; Array.from(setTipForumPostList).forEach((item, index) => { if (window.location.href.match(item["url"])) { setTipForumPostList.splice(index, 1); GM_setValue( "tipToFreeSubjectForumPost", setTipForumPostList ); isRemove = true; utils.setTimeout("window.location.reload()", 1500); return; } }); if (!isRemove) { popups.toast("移出失败"); } else { popups.closeConfirm(); popups.toast({ text: "移出成功", }); } }, }, mask: true, }); }); } else { console.log("未设置提醒"); tipBtnHTML = $jq( `` ); tipBtnHTML.on("click", () => { let expirationTimeMatch = $jq(".kmren") .parent() .text() .replace(/\t|\n/g, "") .match( /[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}[\s]{1}[0-9]{1,2}:[0-9]{1,2}/ ); if (expirationTimeMatch.length == 0) { popups.toast({ text: "获取付费主题到期时间失败", }); return; } let expirationTime = expirationTimeMatch[0]; let expirationTimeStamp = utils.formatToTimeStamp(expirationTime); setTipForumPostList = setTipForumPostList.concat({ url: window.location.href, title: document.title.replace(" - MT论坛", ""), expirationTime: expirationTime, expirationTimeStamp: expirationTimeStamp, isVisited: false, }); GM_setValue("tipToFreeSubjectForumPost", setTipForumPostList); popups.toast({ text: "添加成功", }); setTimeout(function () { window.location.reload(); }, 1500); }); } $jq(".comiis_head.f_top .header_y").append(tipBtnHTML); } } if (storageMatchStatus && urlBBSMatchStatus) { /* 底部导航-我的-提供类似小黑屋这种可查看设置提醒的帖子 */ paymentSubjectReminderHome.insertButtonView(); } if (storageMatchStatus) { /* 设置提醒小红点 */ function getTipNums() { let needTipNums = 0; Array.from(paymentSubjectReminderHome.getData()).forEach( (item, index) => { if ( new Date().getTime() > item["expirationTimeStamp"] && item["isVisited"] == false ) { needTipNums += 1; } } ); return needTipNums; } if ( urlHomeSpaceMatchStatus || urlGuideMatchStatus || urlCommunityMatchStatus ) { /* 当前网页为,底部导航-我的 */ let redBtn = $jq( ".icon_msgs.bg_del.f_f" ); /* 底部导航-我的-右上角小红点 */ let tipNums = 0; if (redBtn.length) { tipNums = parseInt(redBtn.text()); $jq(".icon_msgs.bg_del.f_f").html(tipNums + getTipNums()); $jq(".comiis_head .header_z .kmuser em").append( $jq(``) ); } else { let tipnums = getTipNums(); if (tipnums) { /* $jq("ul.comiis_flex li.flex a[title='我的'] i.comiis_font").append($jq(`${tipnums}`)); */ $jq(".comiis_head .header_z .kmuser em").append( $jq(``) ); } } } if (urlBBSMatchStatus) { /* 当前网页为,全部 */ let redBtn = $jq( ".sidenv_num.bg_del.f_f" ); /* 侧边栏-头像-右上角小红点 */ let tipNums = 0; if (redBtn.length) { tipNums = parseInt(redBtn.text()); $jq(".sidenv_num.bg_del.f_f").html(tipNums + getTipNums()); } else { let tipnums = getTipNums(); if (tipnums) { $jq(".sidenv_user em").before( $jq(`${tipnums}`) ); } } if (getTipNums()) { /* 当前网页为,侧边slider,付费白嫖列表 */ /* $jq(".comiis_left_Touch .paymentsubjectreminder div.flex").append($jq(``)); */ $jq(".comiis_left_Touch .paymentsubjectreminder div.flex").append( $jq(``) ); } } } }, /** * 发帖、回复、编辑预览功能 */ previewPostForum() { GM_addStyle(` #comiis_mh_sub{height:40px} .gm_plugin_word_count{display:flex} .gm_plugin_word_count::after{content:"/20000"} .gm_plugin_previewpostforum_html .comiis_message_table{margin-top:10px;font-weight:initial;line-height:24px} .gm_plugin_previewpostforum_html .comiis_message_table a{height:auto;float:unset;color:#507daf!important} .gm_plugin_previewpostforum_html .comiis_message_table i{text-align:unset;font-size:unset;line-height:unset;padding-top:unset;display:unset} .comiis_postli.comiis_list_readimgs.nfqsqi{width:100vw} .gm_plugin_previewpostforum_html.double-preview{width:50vw} .gm_plugin_previewpostforum_html.double-preview .comiis_over_box.comiis_input_style{border-left:1px solid} `); let open_double = GM_getValue( "preview_post_forum_by_double", "comiis_checkbox_close" ); /** * 添加底部菜单,包括预览、当前字数 */ function addBottomMenu() { $jq("#comiis_mh_sub .swiper-wrapper.comiis_post_ico").append( $jq( `预览` ) ); $jq("#comiis_mh_sub .swiper-wrapper.comiis_post_ico").append( $jq( `

    0

    ` ) ); } /** * 添加底部菜单-高级-使用双列预览 */ function addMenu_doubleColumnPreview() { $jq("#htmlon") .parent() .append( $jq(`
  • 使用双列预览
  • `) ); $jq("#postformdouble").on("click", function () { let obj = $jq(this); let code_obj = obj.parent().find(".comiis_checkbox"); if (code_obj.hasClass("comiis_checkbox_close")) { GM_setValue("preview_post_forum_by_double", true); } else { GM_setValue("preview_post_forum_by_double", false); } }); } /** * 添加底部菜单-高级-使用沉浸输入 */ function addMenu_immersiveInput() { $jq("#htmlon") .parent() .append( $jq(`
  • 使用沉浸输入
  • `) ); $jq("#immersiveinput").on("click", function () { let obj = $jq(this); let code_obj = obj.parent().find(".comiis_checkbox"); console.log(code_obj.attr("class")); if (code_obj.hasClass("comiis_checkbox_close")) { $jq(".comiis_wzpost ul li.comiis_flex").hide(); /* 板块、标题 */ $jq( ".comiis_wzpost ul li.comiis_styli.kmquote" ).hide(); /* 回复别人的quote */ $jq("#pollchecked") .parent() .parent() .hide(); /* 投票,最多可填写 20 个选项 */ $jq("#pollm_c_1").hide(); /* 投票,增加一项 */ $jq( ".comiis_polloption_add+div.f_0" ).hide(); /* 投票,增加一项(编辑状态下) */ $jq( ".comiis_wzpost ul li.comiis_thread_content:contains('内容')" ).hide(); /* 投票,内容 */ $jq("div#comiis_head").hide(); /* 顶部header */ if (!$jq("div#comiis_head").next().attr("class")) { $jq("div#comiis_head").next().hide(); /* 后面的 */ } } else { $jq(".comiis_wzpost ul li.comiis_flex").show(); $jq(".comiis_wzpost ul li.comiis_styli.kmquote").show(); $jq("#pollchecked").parent().parent().show(); $jq("#pollm_c_1").show(); $jq(".comiis_polloption_add+div.f_0").show(); $jq( ".comiis_wzpost ul li.comiis_thread_content:contains('内容')" ).show(); $jq("div#comiis_head").show(); if (!$jq("div#comiis_head").next().attr("class")) { $jq("div#comiis_head").next().show(); } } window.dispatchEvent(new Event("resize")); }); } /** * 表情字典 */ const smiliesDictionaries = { "[呵呵]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq001.gif", "[撇嘴]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq002.gif", "[色]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq003.gif", "[发呆]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq004.gif", "[得意]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq005.gif", "[流泪]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq006.gif", "[害羞]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq007.gif", "[闭嘴]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq008.gif", "[睡]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq009.gif", "[大哭]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq010.gif", "[尴尬]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq011.gif", "[发怒]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq012.gif", "[调皮]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq013.gif", "[呲牙]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq014.gif", "[惊讶]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq015.gif", "[难过]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq016.gif", "[酷]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq017.gif", "[冷汗]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq018.gif", "[抓狂]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq019.gif", "[吐]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq020.gif", "[偷笑]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq021.gif", "[可爱]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq022.gif", "[白眼]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq023.gif", "[傲慢]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq024.gif", "[饥饿]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq025.gif", "[困]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq026.gif", "[惊恐]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq027.gif", "[流汗]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq028.gif", "[憨笑]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq029.gif", "[装逼]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq030.gif", "[奋斗]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq031.gif", "[咒骂]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq032.gif", "[疑问]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq033.gif", "[嘘]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq034.gif", "[晕]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq035.gif", "[折磨]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq036.gif", "[衰]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq037.gif", "[骷髅]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq038.gif", "[敲打]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq039.gif", "[再见]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq040.gif", "[擦汗]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq041.gif", "[抠鼻]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq042.gif", "[鼓掌]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq043.gif", "[糗大了]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq044.gif", "[坏笑]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq045.gif", "[左哼哼]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq046.gif", "[右哼哼]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq047.gif", "[哈欠]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq048.gif", "[鄙视]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq049.gif", "[委屈]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq050.gif", "[快哭了]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq051.gif", "[阴脸]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq052.gif", "[亲亲]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq053.gif", "[吓]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq054.gif", "[可怜]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq055.gif", "[眨眼睛]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq056.gif", "[笑哭]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq057.gif", "[dogeQQ]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq058.gif", "[泪奔]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq059.gif", "[无奈]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq060.gif", "[托腮]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq061.gif", "[卖萌]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq062.png", "[斜眼笑]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq063.gif", "[喷血]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq064.gif", "[惊喜]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq065.gif", "[骚扰]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq066.gif", "[小纠结]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq067.gif", "[我最美]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq068.gif", "[菜刀]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq069.gif", "[西瓜]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq070.gif", "[啤酒]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq071.gif", "[篮球]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq072.gif", "[乒乓]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq073.gif", "[咖啡]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq074.gif", "[饭]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq075.gif", "[猪]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq076.gif", "[玫瑰]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq077.gif", "[凋谢]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq078.gif", "[示爱]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq079.gif", "[爱心]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq080.gif", "[心碎]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq081.gif", "[蛋糕]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq082.gif", "[闪电]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq083.gif", "[炸弹]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq084.gif", "[刀]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq085.gif", "[足球]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq086.gif", "[瓢虫]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq087.gif", "[便便]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq088.gif", "[月亮]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq089.gif", "[太阳]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq090.gif", "[礼物]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq091.gif", "[抱抱]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq092.gif", "[喝彩]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq93.gif", "[祈祷]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq94.gif", "[棒棒糖]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq95.gif", "[药]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq96.gif", "[赞]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq097.gif", "[差劲]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq098.gif", "[握手]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq099.gif", "[胜利]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq100.gif", "[抱拳]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq101.gif", "[勾引]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq102.gif", "[拳头]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq103.gif", "[差劲]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq104.gif", "[爱你]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq105.gif", "[NO]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq106.gif", "[OK]": "https://cdn-bbs.mt2.cn/static/image/smiley/qq/qq107.gif", "[#呵呵]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_1.png", "[#滑稽]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_10.png", "[#吐舌]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_3.png", "[#哈哈]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_2.png", "[#啊]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_23.png", "[#酷]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_22.png", "[#怒]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_13.png", "[#开心]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_39.png", "[#汗]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_14.png", "[#泪]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_16.png", "[#黑线]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_15.png", "[#鄙视]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_21.png", "[#不高兴]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_12.png", "[#真棒]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_17.png", "[#钱]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_40.png", "[#疑问]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_26.png", "[#阴险]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_20.png", "[#吐]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_34.png", "[#咦]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_41.png", "[#委屈]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_29.png", "[#花心]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_6.png", "[#呼~]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_42.png", "[#激动]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_5.png", "[#冷]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_43.png", "[#可爱]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_4.png", "[#What?]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_25.png", "[#勉强]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_38.png", "[#狂汗]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_24.png", "[#酸爽]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_27.png", "[#乖]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_8.png", "[#雅美蝶]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_28.png", "[#睡觉]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_31.png", "[#惊哭]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_19.png", "[#哼]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_44.png", "[#笑尿]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_32.png", "[#惊讶]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_30.png", "[#小乖]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_7.png", "[#喷]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_18.png", "[#抠鼻]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_33.png", "[#捂嘴笑]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_9.png", "[#你懂的]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_11.png", "[#犀利]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_35.png", "[#小红脸]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_36.png", "[#懒得理]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_37.png", "[#爱心]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_45.png", "[#心碎]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_46.png", "[#玫瑰]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_47.png", "[#礼物]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_48.png", "[#彩虹]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_49.png", "[#太阳]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_50.png", "[#月亮]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_51.png", "[#钱币]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_52.png", "[#咖啡]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_53.png", "[#蛋糕]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_54.png", "[#大拇指]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_55.png", "[#胜利]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_56.png", "[#爱你]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_57.png", "[#OK]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_58.png", "[#弱]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_59.png", "[#沙发]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_60.png", "[#纸巾]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_61.png", "[#香蕉]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_62.png", "[#便便]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_63.png", "[#药丸]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_64.png", "[#红领巾]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_65.png", "[#蜡烛]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_66.png", "[#三道杠]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_67.png", "[#音乐]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_68.png", "[#灯泡]": "https://cdn-bbs.mt2.cn/static/image/smiley/comiis_tb/tb_69.png", "[doge]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/1.png", "[doge思考]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/2.png", "[doge再见]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/3.png", "[doge生气]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/4.png", "[doge气哭]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/5.png", "[doge笑哭]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/7.png", "[doge调皮]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/6.png", "[doge啊哈]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/8.png", "[doge原谅TA]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/9.png", "[miao]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/10.png", "[miao思考]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/11.png", "[miao拜拜]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/12.png", "[miao生气]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/13.png", "[miao气哭]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/14.png", "[二哈]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/15.png", "[摊手]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/19.png", "[w并不简单]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/20.png", "[w滑稽]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/21.png", "[w色]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/22.png", "[w爱你]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/23.png", "[w拜拜]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/24.png", "[w悲伤]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/25.png", "[w鄙视]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/26.png", "[w馋嘴]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/27.png", "[w冷汗]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/28.png", "[w打哈欠]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/29.png", "[w打脸]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/30.png", "[w敲打]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/31.png", "[w生病]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/32.png", "[w闭嘴]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/33.png", "[w鼓掌]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/34.png", "[w哈哈]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/35.png", "[w害羞]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/36.png", "[w呵呵]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/37.png", "[w黑线]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/38.png", "[w哼哼]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/39.png", "[w调皮]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/40.png", "[w可爱]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/41.png", "[w可怜]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/42.png", "[w酷]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/43.png", "[w困]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/44.png", "[w懒得理你]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/45.png", "[w流泪]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/46.png", "[w怒]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/47.png", "[w怒骂]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/48.png", "[w钱]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/49.png", "[w亲亲]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/50.png", "[w傻眼]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/51.png", "[w便秘]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/52.png", "[w失望]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/53.png", "[w衰]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/54.png", "[w睡觉]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/55.png", "[w思考]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/56.png", "[w开心]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/57.png", "[w色舔]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/58.png", "[w偷笑]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/59.png", "[w吐]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/60.png", "[w抠鼻]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/61.png", "[w委屈]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/62.png", "[w笑哭]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/63.png", "[w嘻嘻]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/64.png", "[w嘘]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/65.png", "[w阴险]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/66.png", "[w疑问]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/67.png", "[w抓狂]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/70.png", "[w晕]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/69.png", "[w右哼哼]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/68.png", "[w左哼哼]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/71.png", "[w肥皂]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/77.png", "[w奥特曼]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/78.png", "[w草泥马]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/79.png", "[w兔子]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/80.png", "[w熊猫]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/81.png", "[w猪头]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/82.png", "[w→_→]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/83.png", "[w给力]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/84.png", "[w囧]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/85.png", "[w萌]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/86.png", "[w神马]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/87.png", "[w威武]": "https://cdn-bbs.mt2.cn/static/image/smiley/doge/88.png", }; /** * 预览按钮点击事件 * @param {Event} e */ function previewBtnClickEvent() { if ($jq("#polldatas").length) { /* 当前是投票帖子 */ replaceVote(); } if (!$jq(this).find("i.comiis_font").hasClass("f_0")) { $jq(".gm_plugin_previewpostforum_html").css("display", "block"); let replaecdText = replaceText($jq("#needmessage").val()); $jq( ".gm_plugin_previewpostforum_html .comiis_message_table" )[0].innerHTML = replaecdText; if (open_double) { $jq( ".gm_plugin_previewpostforum_html.double-preview .comiis_over_box.comiis_input_style" ).css("height", $jq("#needmessage").css("height")); } } else { $jq(".gm_plugin_previewpostforum_html").hide(); } } /** * 替换内容 * @param {string} text * @returns */ function replaceText(text) { let attachimgmatch = text.match( /\[attachimg\]([\s\S]+?)\[\/attachimg\]/g ); if (attachimgmatch) { attachimgmatch.forEach((item) => { let aimgidMatch = item.match( /\[attachimg\]([\s\S]+?)\[\/attachimg\]/ ); let aimg_id = aimgidMatch ? aimgidMatch[aimgidMatch.length - 1] : ""; let imgtitle = $jq(`#aimg_${aimg_id}`).attr("title"); let imgsrc = $jq(`#aimg_${aimg_id}`).attr("src"); if (!imgsrc) { imgtitle = "该图片不存在"; } text = text.replace( item, `${imgtitle}` ); }); } let code = text.match(/\[code\]([\s\S]*?)\[\/code\]/g); if (code) { code.forEach((item) => { let match_content = item.match(/\[code\]([\s\S]*?)\[\/code\]/); let contentAll = match_content ? match_content[match_content.length - 1] : ""; let content = ""; let brSplit = contentAll.split("\n"); if (brSplit.length == 1) { content = `
  • ${contentAll}
  • `; } else { Array.from(brSplit).forEach((item, index) => { if (index == brSplit.length - 1) { content = `${content}
  • ${item}
  • `; } else { content = `${content}
  • ${item}
  • `; } }); } text = text.replace( item, `
      ${content}
    ` ); }); } let url = text.match(/\[url\=[\s\S]*?\]([\s\S]*?)\[\/url\]/g); if (url) { url.forEach((item) => { let urlMatch = item.match(/\[url=([\s\S]*?)\][\s\S]*\[\/url\]/); let urlNameMatch = item.match( /\[url=[\s\S]*?\]([\s\S]*?)\[\/url\]/ ); let _url_ = urlMatch ? urlMatch[urlMatch.length - 1] : ""; let _url_name_ = urlNameMatch ? urlNameMatch[urlNameMatch.length - 1] : ""; text = text.replace( item, `${_url_name_}` ); }); } let color = text.match(/\[color\=[\s\S]*?\]([\s\S]*?)\[\/color\]/g); if (color) { color.forEach((item) => { let colorValueMatch = item.match( /\[color=([\s\S]*?)\][\s\S]*\[\/color\]/ ); let colorTextMatch = item.match( /\[color=[\s\S]*?\]([\s\S]*?)\[\/color\]/ ); let colorValue = colorValueMatch ? colorValueMatch[colorValueMatch.length - 1] : ""; let colorText = colorTextMatch ? colorTextMatch[colorTextMatch.length - 1] : ""; text = text.replace( item, `${colorText}` ); }); } let size = text.match(/\[size\=[\s\S]*?\]([\s\S]*?)\[\/size\]/g); if (size) { console.log(size); size.forEach((item) => { let sizeValueMatch = item.match( /\[size=([\s\S]*?)\][\s\S]*\[\/size\]/ ); let sizeTextMatch = item.match( /\[size=[\s\S]*?\]([\s\S]*?)\[\/size\]/ ); let sizeValue = sizeValueMatch ? sizeValueMatch[sizeValueMatch.length - 1] : ""; let sizeText = sizeTextMatch ? sizeTextMatch[sizeTextMatch.length - 1] : ""; text = text.replace( item, `${sizeText}` ); }); } let img = text.match(/\[img(|\=[\s\S]+?)\]([\s\S]*?)\[\/img\]/g); if (img) { img.forEach((item) => { let widthInfo = null; let heightInfo = null; let img_size_match = item.match( /\[img\=([\s\S]+?)\][\s\S]*?\[\/img\]/ ); if (img_size_match) { img_size_match = img_size_match[img_size_match.length - 1].split(","); widthInfo = img_size_match[0]; heightInfo = img_size_match[1]; } widthInfo = widthInfo ? widthInfo : ""; heightInfo = heightInfo ? heightInfo : ""; let match_content = item.match( /\[img\]([\s\S]*?)\[\/img\]|\[img=[\s\S]*?\]([\s\S]*?)\[\/img\]/ ); let content = ""; if (match_content) { if (match_content[match_content.length - 1] == null) { content = match_content[match_content.length - 2]; } else { content = match_content[match_content.length - 1]; } } text = text.replace( item, `` ); }); } let hide = text.match(/\[hide\]([\s\S]*?)\[\/hide\]/g); if (hide) { hide.forEach((item) => { let match_content = item.match(/\[hide\]([\s\S]*?)\[\/hide\]/); let content = match_content ? match_content[match_content.length - 1] : ""; text = text.replace( item, `

    本帖隐藏的内容:

    ${content}
    ` ); }); } let hide2 = text.match(/\[hide=[\s\S]*?\]([\s\S]*?)\[\/hide\]/g); if (hide2) { hide2.forEach((item) => { let match_content = item.match( /\[hide=([\s\S]*?)\]([\s\S]*?)\[\/hide\]/ ); let other_info = match_content ? match_content[match_content.length - 2] : ""; other_info = other_info.split(","); let integral_big_can_see = other_info.length == 2 ? other_info[1] : ""; text = text.replace( item, `
    以下内容需要积分高于 ${integral_big_can_see} 才可浏览
    ` ); }); } let quote = text.match(/\[quote\]([\s\S]*?)\[\/quote\]/g); if (quote) { quote.forEach((item) => { let match_content = item.match(/\[quote\]([\s\S]*?)\[\/quote\]/); let content = match_content ? match_content[match_content.length - 1] : ""; text = text.replace( item, `
    回复 ${content}
    ` ); }); } let free = text.match(/\[free\]([\s\S]*?)\[\/free\]/g); if (free) { free.forEach((item) => { let match_content = item.match(/\[free\]([\s\S]*?)\[\/free\]/); let content = match_content ? match_content[match_content.length - 1] : ""; text = text.replace( item, `
    ${content}
    ` ); }); } let strong = text.match(/\[b\]([\s\S]*?)\[\/b\]/g); if (strong) { strong.forEach((item) => { let match_content = item.match(/\[b\]([\s\S]*?)\[\/b\]/i); let content = match_content ? match_content[match_content.length - 1] : ""; text = text.replace(item, `${content}`); }); } let xhx = text.match(/\[u\]([\s\S]*?)\[\/u\]/g); if (xhx) { xhx.forEach((item) => { let match_content = item.match(/\[u\]([\s\S]*?)\[\/u\]/); let content = match_content ? match_content[match_content.length - 1] : ""; text = text.replace(item, `${content}`); }); } let qx = text.match(/\[i\]([\s\S]*?)\[\/i\]/g); if (qx) { qx.forEach((item) => { let match_content = item.match(/\[i\]([\s\S]*?)\[\/i\]/); let content = match_content ? match_content[match_content.length - 1] : ""; text = text.replace(item, `${content}`); }); } let strike = text.match(/\[s\]([\s\S]*?)\[\/s\]/g); if (strike) { strike.forEach((item) => { let match_content = item.match(/\[s\]([\s\S]*?)\[\/s\]/); let content = match_content ? match_content[match_content.length - 1] : ""; text = text.replace(item, `${content}`); }); } let smilies = text.match(/\[([\s\S]+?)\]/g); if (smilies) { smilies.forEach((item) => { console.log(item); let smiliesMatchSrc = smiliesDictionaries[item]; if (smiliesMatchSrc) { text = text.replace( item, `` ); } }); } let media = text.match(/\[media=[\s\S]+?\][\s\S]+?\[\/media\]/g); if (media) { media.forEach((item) => { console.log(item); let match_content = item.match( /\[media=[\s\S]*?\]([\s\S]*?)\[\/media\]/ ); let content = match_content ? match_content[match_content.length - 1] : ""; if (content) { text = text.replace( item, `` ); } }); } let email = text.match(/\[email=[\s\S]+?\][\s\S]+?\[\/email\]/g); if (email) { email.forEach((item) => { console.log(item); let email_match = item.match( /\[email=([\s\S]*?)\][\s\S]*?\[\/email\]/ ); let content_match = item.match( /\[email=[\s\S]*?\]([\s\S]*?)\[\/email\]/ ); let _email_ = email_match.length ? email_match[email_match.length - 1] : ""; let _content_ = content_match.length ? content_match[content_match.length - 1] : ""; if (_email_ || _content_) { text = text.replace( item, `${_content_}` ); } }); } let align = text.match(/\[align=[\s\S]+?\][\s\S]+?\[\/align\]/g); if (align) { align.forEach((item) => { console.log(item); let align_match = item.match( /\[align=([\s\S]*?)\][\s\S]+?\[\/align\]/ ); let content_match = item.match( /\[align=[\s\S]*?\]([\s\S]+?)\[\/align\]/ ); let _align_ = align_match.length ? align_match[align_match.length - 1] : ""; let _content_ = content_match.length ? content_match[content_match.length - 1] : ""; if (_align_ || _content_) { text = text.replace( item, `
    ${_content_}
    ` ); } }); } let qq = text.match(/\[qq\][\s\S]*?\[\/qq\]/g); if (qq) { qq.forEach((item) => { console.log(item); let match_content = item.match(/\[qq\]([\s\S]*?)\[\/qq\]/); let content = match_content ? match_content[match_content.length - 1] : ""; /* 这个是以前的wpa协议,现在是tencent协议,mt的discuz没有更新,如:tencent://message/?uin=xxx&site=bbs.binmt.cc&menu=yes */ text = text.replace( item, `` ); }); } let td = text.match(/\[td\][\s\S]+?\[\/td\]/g); if (td) { td.forEach((item) => { console.log(item); let match_content = item.match(/\[td\]([\s\S]*?)\[\/td\]/); let content = match_content ? match_content[match_content.length - 1] : ""; text = text.replace(item, `${content}`); }); } let tr = text.match(/\[tr\][\s\S]+?\[\/tr\]/g); if (tr) { tr.forEach((item) => { console.log(item); let match_content = item.match(/\[tr\]([\s\S]*?)\[\/tr\]/); let content = match_content ? match_content[match_content.length - 1] : ""; text = text.replace(item, `${content}`); }); } let table = text.match(/\[table\][\s\S]+?\[\/table\]/g); if (table) { table.forEach((item) => { console.log(item); let match_content = item.match(/\[table\]([\s\S]*?)\[\/table\]/); let content = match_content ? match_content[match_content.length - 1] : ""; content = content.replace(/\n/g, ""); text = text.replace(item, `${content}
    `); }); } let list = text.match(/\[list=[\s\S]+?\][\s\S]+?\[\/list\]/g); if (list) { list.forEach((item) => { console.log(item); let list_model_match = item.match( /\[list=([\s\S]*?)\][\s\S]*?\[\/list\]/ ); let list_content_match = item.match( /\[list=[\s\S]*?\]([\s\S]*?)\[\/list\]/ ); let list_model = list_model_match ? list_model_match[list_model_match.length - 1] : ""; let list_type = ""; if (list_model === "a") { list_type = "litype_2"; } else if (list_model === "A") { list_type = "litype_3"; } else if ( list_model.length === 1 && list_model.match(/[0-9]{1}/) ) { list_type = "litype_1"; } let content = list_content_match ? list_content_match[list_content_match.length - 1] : ""; let li_split = content.split("[*]"); if (li_split.length > 1) { let newContent = ""; if (li_split[0].replace(/[\s]*/, "") == "") { li_split = li_split.slice(1); } Array.from(li_split).forEach((item) => { newContent = `${newContent}
  • ${item}
  • `; }); content = newContent; } content = content.replace(/\n/g, ""); text = text.replace( item, `
      ${content}
    ` ); }); } $jq( ".gm_plugin_previewpostforum_html .comiis_quote.comiis_qianglou" ).remove(); let password = text.match(/\[password\](.*?)\[\/password\]/gi); if (password) { password.forEach((item) => { console.log(item); text = item.replace(/\[password\](.*?)\[\/password\]/gi, ""); $jq( ".gm_plugin_previewpostforum_html .comiis_message_table" ).before( $jq(`
     付费主题, 价格: ${$jq( "#price" ).val()} 金币 记录
    `) ); }); } let every_reward = parseInt($jq("#replycredit_extcredits").val()); let total_reward = parseInt($jq("#replycredit_times").val()); let getreward_menbertimes = parseInt( $jq("#replycredit_membertimes").val() ); let getreward_random = parseInt($jq("#replycredit_random").val()); $jq(".gm_plugin_previewpostforum_html .comiis_htjl").remove(); if ( !isNaN(every_reward) && !isNaN(total_reward) && every_reward > 0 && total_reward > 0 ) { $jq(".gm_plugin_previewpostforum_html .comiis_message_table").before( $jq(`
    总共奖励 ${total_reward} 金币
    回复本帖可获得 ${every_reward} 金币奖励! 每人限 ${getreward_menbertimes} 次 ${ getreward_random != 100 ? `(中奖概率 ${getreward_random}%)` : "" }
    `) ); } text = text.replace(/\[hr\]/g, '
    '); text = text.replace(/\[\*\]/g, "
  • "); text = text.replace(/\n/g, "
    "); return text; } function replaceVote() { /* 替换预览投票 */ let chooseColor = [ "rgb(233, 39, 37)", "rgb(242, 123, 33)", "rgb(242, 166, 31)", "rgb(90, 175, 74)", "rgb(66, 196, 245)", "rgb(0, 153, 204)", "rgb(51, 101, 174)", "rgb(42, 53, 145)", "rgb(89, 45, 142)", "rgb(219, 49, 145)", "rgb(233, 39, 37)", "rgb(242, 123, 33)", "rgb(242, 166, 31)", "rgb(90, 175, 74)", "rgb(66, 196, 245)", "rgb(0, 153, 204)", "rgb(51, 101, 174)", "rgb(42, 53, 145)", "rgb(89, 45, 142)", "rgb(219, 49, 145)", ]; /* 选择的背景 */ let chooseContent = $jq( ".comiis_polloption_add ul li:first-child div.flex .comiis_input.kmshow[type='text']" ); /* 选项,最多20个 */ let maxchoices = parseInt($jq("input#maxchoices").val()); /* 最多可选 */ maxchoices = isNaN(maxchoices) ? 0 : maxchoices; maxchoices = maxchoices > 0 ? maxchoices : 0; maxchoices = maxchoices > chooseContent.length ? chooseContent.length : maxchoices; /* 大于当前选项数量的话为当前最大选项数量 */ let polldatas = parseInt($jq("input#polldatas").val()); /* 记票天数 */ polldatas = isNaN(polldatas) ? 0 : polldatas; let visibilitypoll = $jq("input#visibilitypoll") .parent() .find(".comiis_checkbox") .hasClass("comiis_checkbox_close") ? false : true; /* 投票后结果可见 */ let overt = $jq("input#overt") .parent() .find(".comiis_checkbox") .hasClass("comiis_checkbox_close") ? false : true; /* 公开投票参与人 */ let html = ""; let choosehtml = ""; console.log(chooseContent); chooseContent.each((index, item) => { if (index >= 20) { /* 最多20个 */ return; } choosehtml = choosehtml + `
  • 0% (0)
  • `; }); html = `

    ${ maxchoices > 1 ? "多选投票" + ' 最多可选 ' + maxchoices + " 项" : "单选投票" }

    共有 0 人参与投票

    ${ polldatas > 0 ? `

    距结束还有: ${ polldatas > 1 ? '' + (polldatas - 1) + " 天 " : "" }23 小时 59 分钟

    ` : "" }
      ${choosehtml}
    ${ overt ? '
    此为公开投票,其他人可看到您的投票项目
    ' : "" }
    `; $jq(".gm_plugin_previewpostforum_html .postforum_vote").remove(); $jq( ".gm_plugin_previewpostforum_html .comiis_messages.comiis_aimg_show" ) .children() .eq(0) .before($jq(html)); } /** * 内容输入事件 * @param {Event} event */ function keyUpEvent(event) { let userInputText = event.target.value; let userInputTextLength = utils.getTextLength(userInputText); let replaecdText = replaceText(userInputText); $jq( ".gm_plugin_previewpostforum_html .comiis_message_table" )[0].innerHTML = replaecdText; let wordCountDom = $jq(".gm_plugin_word_count p"); wordCountDom.text(userInputTextLength); if (userInputTextLength > 20000 || userInputTextLength < 10) { wordCountDom.attr("style", "color: red;"); } else { wordCountDom.attr("style", ""); } } if (typeof unsafeWindow.comiis_addsmilies == "function") { /* 替换全局函数添加图片到里面触发input */ unsafeWindow.comiis_addsmilies = (_str_) => { unsafeWindow.$("#needmessage").comiis_insert(_str_); unsafeWindow.$("#needmessage")[0].dispatchEvent(new Event("input")); }; } addMenu_doubleColumnPreview(); addBottomMenu(); addMenu_immersiveInput(); if (open_double) { /* box-shadow: -1px 0px 8px; */ $jq("#needmessage").parent().css("display", "flex"); $jq("#needmessage").after( $jq(` `) ); } else { $jq("#comiis_post_tab").append( $jq(` `) ); } $jq("#needmessage").on("propertychange input", keyUpEvent); $jq(".gm_plugin_previewpostforum").on("click", previewBtnClickEvent); }, /** * 积分商城商品上架提醒 */ productReminder() { /** * 初始化DOM元素到页面中 */ function setDom() { GM_addStyle(` #productReminder{border-radius:0} #productReminder .styli_tit i{color:#2376b7!important} #productReminder a.comiis_flex{border-top:1px solid #efefef!important} #productNameInput{width:-webkit-fill-available;width:-moz-available;height:30px;margin:8px 20px;border:0;border-bottom:1px solid;text-overflow:ellipsis;overflow:hidden;white-space:nowrap} `); GM_addStyle(` .NZ-MsgBox-alert .productItem{display:flex;align-items:center} .NZ-MsgBox-alert .productDivFlex{display:flex;align-items:center;margin:16px 10px;width:100%} .NZ-MsgBox-alert .productItem i.comiis_font{font-size:24px;padding:0 6px} `); const productReminderBtnHTML = ` `; $jq(".comiis_myinfo").append($jq(productReminderBtnHTML)); } /** * 为DOM元素设置事件 */ function setDomEvent() { $jq("#productReminder").on("click", function () { $jq.NZ_MsgBox.confirm({ title: "积分商城商品上架提醒", content: "
    检索中...
    ", type: "", location: "center", buttons: { autoClose: false, reverse: true, confirm: { text: "添加", }, cancel: { text: "关闭", }, }, callback: function (status, closeCallBack) { if (status) { setAddBtnClickEvent(); } else { closeCallBack(); } }, }); setViewData(); }); } /** * 设置编辑按钮点击事件 * @param {HTMLElement} itemDOM 元素 * @param {Object} data 数据 */ function setEditClickEvent(itemDOM, data) { itemDOM.on("click", "i[data-flag='edit']", function () { setAddBtnClickEvent(data, true); }); } /** * 设置删除按钮点击事件 * @param {HTMLElement} itemDOM 元素 * @param {Object} data 数据 */ function setDeleteClickEvent(itemDOM, data) { itemDOM.on("click", "i[data-flag='delete']", function () { popups.confirm({ text: "确定删除该条数据?", ok: { callback: () => { deleteLocalData(data); itemDOM.remove(); popups.closeMask(); popups.closeConfirm(); popups.toast("删除成功"); }, }, }); }); } /** * 为弹出的视图设置数据 */ function setViewData() { let data = getLocalData(); if (data.length === 0) { $jq(".NZ-MsgBox-alert .msgcon").html("
    暂无数据
    "); return; } let dataDOM = $jq(`
  • `); data.forEach((item) => { let itemDOM = $jq(`

    ${item["name"]}

    `); setEditClickEvent(itemDOM, item); setDeleteClickEvent(itemDOM, item); dataDOM.append(itemDOM); }); $jq(".NZ-MsgBox-alert .msgcon").html(dataDOM); } /** * 获取本地数据 * @returns {Array} */ function getLocalData() { return GM_getValue("productReminderList", []); } /** * 设置本地数据 * @param {Object} data 数据,{name:""} * @returns {Boolean} 是否添加成功 */ function setLocalData(data) { let dataString = JSON.stringify(data); let localData = getLocalData(); let status = true; localData.forEach((item) => { if (JSON.stringify(item) === dataString) { status = false; return; } }); if (status) { localData = localData.concat(data); GM_setValue("productReminderList", localData); } return status; } /** * 修改本地数据 * @param {{name:string}} oldData 旧数据,{name:""} * @param {{name:string}} newData 新数据, {name:""} * @returns {boolean} 是否修改成功 */ function changeLocalData(oldData, newData) { let oldDataString = JSON.stringify(oldData); let localData = getLocalData(); let status = false; localData.map((item) => { if (JSON.stringify(item) === oldDataString) { status = true; item = utils.assign(item, newData); return; } }); if (status) { GM_setValue("productReminderList", localData); } return status; } /** * 删除本地数据 * @param {{name:string}} data 需要被删除的数据,{name:""} * @returns {boolean} 是否删除成功 */ function deleteLocalData(data) { let dataString = JSON.stringify(data); let localData = getLocalData(); let status = false; localData = localData.filter((item) => { if (JSON.stringify(item) === dataString) { status = true; return false; } else { return true; } }); if (status) { GM_setValue("productReminderList", localData); } return status; } /** * 弹出的视图的添加按钮的点击事件 * @param {{name:string}}} defaultData 默认数据 * @param {boolean} isEdit 是否是编辑模式 */ function setAddBtnClickEvent(defaultData = { name: "" }, isEdit = false) { popups.confirm({ text: ` `, ok: { callback: () => { let productName = $jq("#productNameInput").val(); if (utils.isNull(productName)) { popups.toast("请勿输入为空"); return; } let newData = { name: productName, }; let dataString = JSON.stringify(newData); let localData = getLocalData(); let sameData = localData.filter((item) => { return JSON.stringify(item) === dataString ? true : false; }); if (sameData.length) { popups.toast("已存在相同的数据"); return; } if (isEdit) { let changeDataStatus = changeLocalData(defaultData, newData); if (changeDataStatus) { popups.toast("修改成功"); } else { popups.toast("修改失败"); return; } } else { let addDataStatus = setLocalData(newData); if (addDataStatus) { popups.toast("添加成功"); } else { popups.toast("已存在相同的数据"); return; } } popups.closeMask(); popups.closeConfirm(); setViewData(); }, }, }); $jq("#productNameInput").val(defaultData["name"]); $jq("#productNameInput").focus(); } /** * 获取当前积分商城的所有商品 */ async function getCurrentProduct() { return new Promise((resolve) => { GM_xmlhttpRequest({ url: "https://bbs.binmt.cc/keke_integralmall-keke_integralmall.html", method: "GET", async: false, responseType: "html", timeout: 5000, headers: { "User-Agent": utils.getRandomAndroidUA(), }, onload: function (response) { let dataList = []; $jq(response.responseText) .find(".task-list-wrapper li.col-xs-12") .each((index, item) => { dataList = dataList.concat({ name: item.querySelector(".mall-info a").innerText, price: item.querySelector( ".mall-info span.discount-price i" ).innerText, deadLine: item.querySelector( ".mall-info #time_hz span.time" ).innerText, remainingQuantity: parseInt( item .querySelector(".mall-info .mall-count .count-r") ?.innerText?.replace(/仅剩|件/gi, "") ), }); }); resolve(dataList); }, onerror: function () { popups.toast("【积分商城】网络异常,请重新获取"); resolve(null); }, ontimeout: function () { popups.toast("【积分商城】请求超时"); resolve(null); }, }); }); } if (DOM_CONFIG.methodRunCheck([DOM_CONFIG.urlRegexp.homeSpaceUrl])) { setDom(); setDomEvent(); } (async function () { if ( window.location.href.match( /^https:\/\/bbs.binmt.cc\/keke_integralmall/i ) || window.location.href.match( /^https:\/\/bbs.binmt.cc\/plugin.php\?id=keke_integralmal/i ) ) { /* 不在积分商城的界面中弹窗 */ return; } let localData = getLocalData(); if (!localData.length) { return; } console.log("设置的提醒商品", localData); let productList = await getCurrentProduct(); if (!productList) { return; } let flag = false; for (const productItem of productList) { for (const localDataItem of localData) { if ( productItem["name"].match( new RegExp(localDataItem["name"]), "i" ) && !isNaN(productItem["remainingQuantity"]) && productItem["remainingQuantity"] > 0 ) { popups.confirm({ text: `
    您设置的商品已上架在积分商城中,当前售价 ${productItem["price"]}金币,仅剩${productItem["remainingQuantity"]}件,是否前往购买?(如需关闭提醒,请删除该关键字)
    `, ok: { text: "前往购买", callback: () => { window.location.href = "https://bbs.binmt.cc/keke_integralmall-keke_integralmall.html"; }, }, other: { enable: true, text: "删除提醒", callback: () => { if (deleteLocalData(localDataItem)) { popups.toast("删除成功"); } else { popups.toast("删除失败"); } popups.closeConfirm(); popups.closeMask(); }, }, }); flag = true; return; } } if (flag) { return; } } })(); }, /** * 自定义用户标签 */ customizeUserLabels() { const CustomizeUserLabels = { init() { this.setDom(); this.appendSpaceDom(); this.setDomEvent(); }, /** * 初始化DOM元素到页面中 */ setDom() { GM_addStyle(` #customizeUserLabels{border-top-left-radius:0;border-top-right-radius:0} #customizeUserLabels .styli_tit i{color:#c70ea6!important} #customizeUserLabels a.comiis_flex{border-top:1px solid #efefef!important} #customizeUserLabelsColorInput,#customizeUserLabelsInput,#customizeUserLabelsJSInput,#customizeUserLabelsStyleInput,#customizeUserUIDInput{width:-webkit-fill-available;width:-moz-available;height:30px;margin:8px 20px;border:0;border-bottom:1px solid;text-overflow:ellipsis;overflow:hidden;white-space:nowrap} #customizeUserLabelsJSInput,#customizeUserLabelsStyleInput{height:200px;white-space:pre-wrap} .CustomizeUserLabelsFlex,.CustomizeUserLabelsItem{display:flex;align-items:center} .CustomizeUserLabelsItem i[data-flag]{font-size:24px;padding:0 6px} .CustomizeUserLabelsFlex{width:100%;margin:16px 10px} .dialog-input-userlabels{display:flex;align-items:baseline;text-align:left} .dialog-input-userlabels p{width:100px}`); GM_addStyle(` .NZ-MsgBox-alert .productItem{display:flex;align-items:center} .NZ-MsgBox-alert .productDivFlex{display:flex;align-items:center;margin:16px 10px;width:100%} .NZ-MsgBox-alert .productItem i.comiis_font{font-size:24px;padding:0 6px}`); const customizeUserLabelsBtnHTML = ` `; $jq(".comiis_myinfo").append($jq(customizeUserLabelsBtnHTML)); }, /** * 添加空格横栏 */ appendSpaceDom() { $jq(".comiis_myinfo").append($jq('
    ')); }, /** * 为DOM元素设置事件 */ setDomEvent() { $jq("#customizeUserLabels").on("click", function () { $jq.NZ_MsgBox.confirm({ title: "自定义用户标签", content: "
    检索中...
    ", type: "", location: "center", buttons: { autoClose: false, reverse: true, confirm: { text: "添加", }, cancel: { text: "关闭", }, }, callback: function (status, closeCallBack) { if (status) { CustomizeUserLabels.setAddBtnClickEvent(); } else { closeCallBack(); } }, }); CustomizeUserLabels.setViewData(); }); }, /** * 为弹出的视图设置数据 */ setViewData() { let data = CustomizeUserLabels.getData(); if (data.length === 0) { $jq(".NZ-MsgBox-alert .msgcon").html("
    暂无数据
    "); return; } let dataDOM = $jq(`
  • `); data.forEach((item) => { let itemDOM = $jq(`

    ${item["uid"]}

    `); CustomizeUserLabels.setEditClickEvent(itemDOM, item); CustomizeUserLabels.setDeleteClickEvent(itemDOM, item); dataDOM.append(itemDOM); }); $jq(".NZ-MsgBox-alert .msgcon").html(dataDOM); }, /** * 弹出的视图的添加按钮的点击事件 * @param {Object} defaultData 默认数据 * @param {Boolean} isEdit 是否是编辑模式 */ setAddBtnClickEvent( defaultData = { uid: "", labels: [], color: "", style: "", js: "" }, isEdit = false ) { popups.confirm({ text: `

    UID

    标签

    颜色

    CSS

    JS

    `, ok: { callback: () => { let newData = { uid: 0, labels: [], color: "", style: "", js: "", }; let inputUID = $jq("#customizeUserUIDInput").val().trim(); let inputLabels = $jq("#customizeUserLabelsInput").val().trim(); let inputColor = $jq("#customizeUserLabelsColorInput") .val() .trim(); let inputStyle = $jq("#customizeUserLabelsStyleInput") .val() .trim(); let inputJS = $jq("#customizeUserLabelsJSInput").val(); if (utils.isNull(inputUID)) { popups.toast("请输入用户UID"); return; } if (utils.isNull(inputLabels)) { popups.toast("请输入自定义用户标签"); return; } inputUID = parseInt(inputUID); if (isNaN(inputUID)) { popups.toast("请输入正确的UID"); return; } newData.uid = inputUID; newData.labels = inputLabels; newData.color = inputColor; newData.style = inputStyle; newData.js = inputJS; console.log(newData); let localData = CustomizeUserLabels.getData(); let localDataString = JSON.stringify(localData); let sameData = localData.filter((item) => { return JSON.stringify(item) === localDataString; }); if (sameData.length && !isEdit) { popups.toast("已存在相同的,请勿重复添加"); return; } if (isEdit) { let changeDataStatus = CustomizeUserLabels.changeLocalData( defaultData, newData ); if (changeDataStatus) { popups.toast("修改成功"); } else { popups.toast("修改失败"); return; } } else { let addDataStatus = CustomizeUserLabels.setLocalData(newData); if (addDataStatus) { popups.toast("添加成功"); } else { popups.toast("已存在相同的数据"); return; } } popups.closeMask(); popups.closeConfirm(); CustomizeUserLabels.setViewData(); }, }, }); $jq("#customizeUserUIDInput").val(defaultData["uid"]); $jq("#customizeUserLabelsInput").val(defaultData["labels"]); $jq("#customizeUserLabelsColorInput").val(defaultData["color"]); $jq("#customizeUserLabelsStyleInput").val(defaultData["style"]); $jq("#customizeUserLabelsJSInput").val(defaultData["js"]); $jq("#customizeUserUIDInput").focus(); }, /** * 设置编辑按钮点击事件 * @param {HTMLElement} itemDOM 元素 * @param {Object} data 数据 */ setEditClickEvent(itemDOM, data) { itemDOM.on("click", "i[data-flag='edit']", function () { CustomizeUserLabels.setAddBtnClickEvent(data, true); }); }, /** * 设置删除按钮点击事件 * @param {HTMLElement} itemDOM 元素 * @param {Object} data 数据 */ setDeleteClickEvent(itemDOM, data) { itemDOM.on("click", "i[data-flag='delete']", function () { popups.confirm({ text: "确定删除该条数据?", ok: { callback: () => { CustomizeUserLabels.deleteLocalData(data); itemDOM.remove(); popups.closeMask(); popups.closeConfirm(); popups.toast("删除成功"); }, }, }); }); }, /** /** * 获取本地数据 * @returns {Array} */ getData() { return GM_getValue("customizeUserLabelsList", []); }, /** * 设置本地数据 * @param {any} data */ setData(data) { GM_setValue("customizeUserLabelsList", data); }, /** * 修改本地数据 * @param {Object} oldData 旧数据,{name:""} * @param {Object} newData 新数据, {name:""} * @returns {Boolean} 是否修改成功 */ changeLocalData(oldData, newData) { let localData = CustomizeUserLabels.getData(); let status = false; let oldDataString = JSON.stringify(oldData); localData.map((item) => { if (JSON.stringify(item) === oldDataString) { status = true; item = utils.assign(item, newData); return; } }); if (status) { CustomizeUserLabels.setData(localData); } return status; }, /** * 设置本地数据 * @param {object} data 数据,{name:""} * @returns {boolean} 是否添加成功 */ setLocalData(data) { let localData = CustomizeUserLabels.getData(); let dataString = JSON.stringify(data); let status = true; console.log(data); localData.forEach((item) => { if (JSON.stringify(item) === dataString) { status = false; return; } }); if (status) { localData = localData.concat(data); CustomizeUserLabels.setData(localData); } return status; }, /** * 删除本地数据 * @param {Object} data 需要被删除的数据,{name:""} * @returns {Boolean} 是否删除成功 */ deleteLocalData(data) { let localData = CustomizeUserLabels.getData(); let status = false; let dataString = JSON.stringify(data); localData = localData.filter((item) => { if (JSON.stringify(item) === dataString) { status = true; return false; } else { return true; } }); if (status) { CustomizeUserLabels.setData(localData); } return status; }, }; if (DOM_CONFIG.methodRunCheck([DOM_CONFIG.urlRegexp.homeSpaceUrl])) { CustomizeUserLabels.init(); } }, /** * 编辑器中的ubb代码 */ quickUBB: { code: { rainbow1: { key: "转普通彩虹", value: "", isFunc: true, num: 1, }, rainbow2: { key: "转黑白彩虹", value: "", isFunc: true, num: 2, }, rainbow3: { key: "转黑红彩虹", value: "", isFunc: true, num: 3, }, rainbow4: { key: "转蓝绿彩虹", value: "", isFunc: true, num: 4, }, size: { key: "大小", value: "[size=][/size]", tagL: "=", tagR: "]", L: "[size=]", R: "[/size]", cursorL: "[size=", cursorLength: 6, quickUBBReplace: "[size=14]replace[/size]", }, color: { key: "颜色", value: "[color=][/color]", tagL: "=", tagR: "]", L: "[color=]", R: "[/color]", cursorL: "[color=", cursorLength: 7, quickUBBReplace: "[color=#000]replace[/color]", }, b: { key: "加粗", value: "[b][/b]", tagL: "]", tagR: "[", L: "[b]", R: "[/b]", cursorR: "[/b]", cursorLength: 4, quickUBBReplace: "[b]replace[/b]", }, u: { key: "下划线", value: "[u][/u]", tagL: "]", tagR: "[", L: "[u]", R: "[/u]", cursorR: "[/u]", cursorLength: 4, quickUBBReplace: "[u]replace[/u]", }, i: { key: "倾斜", value: "[i][/i]", tagL: "]", tagR: "[", L: "[i]", R: "[/i]", cursorR: "[/i]", cursorLength: 4, quickUBBReplace: "[i]replace[/i]", }, s: { key: "中划线", value: "[s][/s]", tagL: "]", tagR: "[", L: "[s]", R: "[/s]", cursorR: "[/s]", cursorLength: 4, quickUBBReplace: "[s]replace[/s]", }, lineFeed: { key: "换行", value: "[*]", L: "", R: "[*]", cursorL: "[*]", cursorLength: 3, quickUBBReplace: "replace[*]", }, longHorizontalLine: { key: "水平线", value: "[hr]", L: "", R: "[hr]", cursorL: "[hr]", cursorLength: 4, quickUBBReplace: "replace[hr]", }, link: { key: "链接", value: "[url=][/url]", tagL: "=", tagR: "]", L: "[url=]", R: "[/url]", cursorL: "[url=", cursorLength: 5, quickUBBReplace: "[url=replace]replace[/url]", }, hide: { key: "隐藏", value: "[hide]\n[/hide]", tagL: "]", tagR: "[", L: "[hide]", R: "[/hide]", cursorR: "[/hide]", cursorLength: 7, quickUBBReplace: "[hide]replace\n[/hide]", }, quote: { key: "引用", value: "[quote][/quote]", tagL: "]", tagR: "[", L: "[quote]", R: "[/quote]", cursorR: "[/quote]", cursorLength: 8, quickUBBReplace: "[quote]replace[/quote]", }, email: { key: "邮件", value: "[email=][/email]", tagL: "=", tagR: "]", L: "[email=]", R: "[/email]", cursorL: "[email=", cursorLength: 7, quickUBBReplace: "[email=replace]replace[/email]", }, }, /** * 快捷回复 */ insertQuickReplyUBB: () => { let ubbCodeMap = mobile.quickUBB.code; ubbCodeMap["code"] = { key: "代码", value: "[code][/code]", tagL: "]", tagR: "[", L: "[code]", R: "[/code]", cursorL: "[code]", cursorLength: 7, quickUBBReplace: "[code]replace[/code]", }; ubbCodeMap["password"] = { key: "密码", value: "[password][/password]", tagL: "]", tagR: "[", L: "[password]", R: "[/password]", cursorL: "[password]", cursorLength: 10, quickUBBReplace: "[password]replace[/password]", }; $jq.each(ubbCodeMap, function (index, value) { let ubbs = $jq( `
  • ${value["key"]}
  • ` ); ubbs.on("click", function () { $jq( "#comiis_insert_ubb_tab div.comiis_post_urlico ul li.quickUBBs a.comiis_xifont" ) .removeClass("f_0") .addClass("f_d"); $jq(this).find(".comiis_xifont").removeClass("f_d").addClass("f_0"); popups.confirm({ text: ` `, mask: true, only: true, cancel: { callback: () => { GLOBAL_DATA.isUBBCodeInsertClick = true; popups.closeMask(); popups.closeConfirm(); }, }, ok: { callback: () => { GLOBAL_DATA.isUBBCodeInsertClick = true; let userInput = $jq(".quickinsertbbsdialog").val(); if (userInput.trim() === "") { popups.toast({ text: "输入框不能为空或纯空格", }); return; } if (value["isFunc"]) { comiis_addsmilies( mobile.quickUBB.set_rainbow(value["num"], userInput) ); /* 插入贴内 */ } else if (value["quickUBBReplace"]) { comiis_addsmilies( value["quickUBBReplace"].replaceAll("replace", userInput) ); /* 插入贴内 */ } else { comiis_addsmilies(userInput); /* 插入贴内 */ } popups.closeConfirm(); }, }, }); $jq(".quickinsertbbsdialog").focus(); }); $jq("#comiis_insert_ubb_tab div.comiis_post_urlico ul").append( ubbs[0] ); }); }, /** * 具体回复 */ insertReplayUBB: () => { let insertDOM = $jq(".comiis_post_urlico"); if (!insertDOM) { console.log("未找到插入元素"); return; } GM_addStyle(` #comiis_post_tab .comiis_input_style .comiis_post_urlico li a.f_0{ color: #53bcf5 !important; } `); let parentEle = $jq(".comiis_post_urlico > ul")[0]; let contentEle = $jq("#comiis_post_qydiv > ul"); let childNums = $jq("#comiis_post_qydiv ul li").length; mobile.quickUBB.jqueryExtraFunction(); $jq("#comiis_post_tab .comiis_input_style .comiis_post_urlico li").on( "click", function () { $jq( "#comiis_post_tab .comiis_input_style .comiis_post_urlico li a" ).removeClass("f_0"); $jq( "#comiis_post_tab .comiis_input_style .comiis_post_urlico li a" ).addClass("f_d"); $jq(this).find("a").attr("class", "comiis_xifont f_0"); $jq("#comiis_post_qydiv ul li") .hide() .eq($jq(this).index()) .fadeIn(); } ); $jq.each(mobile.quickUBB.code, function (key, value) { let ubbs = $jq( `
  • ${value["key"]}
  • ` ); ubbs.on("click", (event) => { let bottomEle = $jq( `#comiis_post_qydiv li[data-key='${value.key}']` ); if (!bottomEle.length) { console.log("未找到该元素"); return; } let contentIndex = childNums + Object.keys(mobile.quickUBB.code).indexOf(key); console.log(contentIndex); $jq("#comiis_post_qydiv ul li").hide().eq(contentIndex).fadeIn(); $jq.each( $jq( "#comiis_post_tab div.comiis_post_urlico ul li a.comiis_xifont" ), (index, item) => { item.className = "comiis_xifont f_d"; if (item == event.target) { item.className = "comiis_xifont f_0"; } } ); }); parentEle.append(ubbs[0]); let ubbs_content = document.createElement("li"); ubbs_content.setAttribute("style", "display: none;"); ubbs_content.setAttribute("data-key", value["key"]); ubbs_content.innerHTML = `
    `; contentEle.append(ubbs_content); $jq(`.comiis_sendbtn[data-keyI="${key}"]`).on("click", () => { let text = $jq(`#comiis_input_${key}`).val(); if (text == "") { popups.toast("请输入需要插入的内容"); return; } if (mobile.quickUBB.code[key]["isFunc"]) { text = mobile.quickUBB.set_rainbow( mobile.quickUBB.code[key]["num"], text ); } if (mobile.quickUBB.code[key].hasOwnProperty("L")) { text = mobile.quickUBB.code[key]["L"] + text + mobile.quickUBB.code[key]["R"]; } $jq("#needmessage").insertAtCaret(text); /* if (mobile.quickUBB.code[key]["tagL"] != undefined || mobile.quickUBB.code[key]["tagR"] != undefined) { $jq("#needmessage").moveCursorInCenterByText(mobile.quickUBB.code[key]["tagL"], mobile.quickUBB.code[key]["tagR"]); }*/ if (mobile.quickUBB.code[key].hasOwnProperty("cursorL")) { $jq("#needmessage").moveCursorToCenterByTextWithLeft( mobile.quickUBB.code[key]["cursorL"], mobile.quickUBB.code[key]["cursorLength"] ); } if (mobile.quickUBB.code[key].hasOwnProperty("cursorR")) { $jq("#needmessage").moveCursorToCenterByTextWithRight( mobile.quickUBB.code[key]["cursorR"], mobile.quickUBB.code[key]["cursorLength"] ); } }); }); }, set_rainbow: (num, text) => { if (text == "") { return ""; } var wr_text = text; var wr_code, wr_rgb, r, g, b, i, j, istep; var wr_rgb1, wr_rgb2, r1, g1, b1, r2, g2, b2; r1 = g1 = b1 = r2 = g2 = b2 = 0; r = 0; g = 0; b = 0; istep = 0; wr_code = ""; if (num == 1) { istep = 40; r = 255; i = 1; j = 0; do { if (wr_text.charCodeAt(j) != 32) { if (g + istep < 256) { if (i == 1) g += istep; } else if (i == 1) { i = 2; g = 255; } if (r - istep > -1) { if (i == 2) r -= istep; } else if (i == 2) { i = 3; r = 0; } if (b + istep < 256) { if (i == 3) b += istep; } else if (i == 3) { i = 4; b = 255; } if (g - istep > -1) { if (i == 4) g -= istep; } else if (i == 4) { i = 5; g = 0; } if (r + istep < 256) { if (i == 5) r += istep; } else if (i == 5) { i = 6; r = 255; } if (b - istep > -1) { if (i == 6) b -= istep; } else if (i == 6) { i = 1; b = 0; } wr_rgb = ""; wr_rgb += parseInt(r).toString(16).length == 1 ? 0 + parseInt(r).toString(16) : parseInt(r).toString(16); wr_rgb += parseInt(g).toString(16).length == 1 ? 0 + parseInt(g).toString(16) : parseInt(g).toString(16); wr_rgb += parseInt(b).toString(16).length == 1 ? 0 + parseInt(b).toString(16) : parseInt(b).toString(16); wr_rgb = wr_rgb.toUpperCase(); wr_code += `[color=#${wr_rgb}]${wr_text.charAt(j)}[/color]`; } else { wr_code += wr_text.charAt(j); } j++; } while (j < wr_text.length); } else if (num == 2) { istep = 255 / wr_text.length; for (i = 1; i < wr_text.length + 1; i++) { if (wr_text.charCodeAt(i - 1) != 32) { r += istep; g += istep; b += istep; if (r > 255) r = 255; if (g > 255) g = 255; if (b > 255) b = 255; wr_rgb = ""; wr_rgb += parseInt(r).toString(16).length == 1 ? 0 + parseInt(r).toString(16) : parseInt(r).toString(16); wr_rgb += parseInt(g).toString(16).length == 1 ? 0 + parseInt(g).toString(16) : parseInt(g).toString(16); wr_rgb += parseInt(b).toString(16).length == 1 ? 0 + parseInt(b).toString(16) : parseInt(b).toString(16); wr_rgb = wr_rgb.toUpperCase(); wr_code += `[color=#${wr_rgb}]${wr_text.charAt(i - 1)}[/color]`; } else { wr_code += wr_text.charAt(i - 1); } } } else if (num == 3) { istep = 255 / wr_text.length; for (i = 1; i < wr_text.length + 1; i++) { if (wr_text.charCodeAt(i - 1) != 32) { r += istep; g = 29; b = 36; if (r > 255) r = 255; if (g > 255) g = 255; if (b > 255) b = 255; wr_rgb = ""; wr_rgb += parseInt(r).toString(16).length == 1 ? 0 + parseInt(r).toString(16) : parseInt(r).toString(16); wr_rgb += parseInt(g).toString(16).length == 1 ? 0 + parseInt(g).toString(16) : parseInt(g).toString(16); wr_rgb += parseInt(b).toString(16).length == 1 ? 0 + parseInt(b).toString(16) : parseInt(b).toString(16); wr_rgb = wr_rgb.toUpperCase(); wr_code += `[color=#${wr_rgb}]${wr_text.charAt(i - 1)}[/color]`; } else { wr_code += wr_text.charAt(i - 1); } } } else if (num == 4) { istep = 255 / wr_text.length; for (i = 1; i < wr_text.length + 1; i++) { if (wr_text.charCodeAt(i - 1) != 32) { r = 0; g = 174; b += istep; if (r > 255) r = 255; if (g > 255) g = 255; if (b > 255) b = 255; wr_rgb = ""; wr_rgb += parseInt(r).toString(16).length == 1 ? 0 + parseInt(r).toString(16) : parseInt(r).toString(16); wr_rgb += parseInt(g).toString(16).length == 1 ? 0 + parseInt(g).toString(16) : parseInt(g).toString(16); wr_rgb += parseInt(255 - b).toString(16).length == 1 ? 0 + parseInt(255 - b).toString(16) : parseInt(255 - b).toString(16); wr_rgb = wr_rgb.toUpperCase(); wr_code += `[color=#${wr_rgb}]${wr_text.charAt(i - 1)}[/color]`; } else { wr_code += wr_text.charAt(i - 1); } } } return wr_code; }, jqueryExtraFunction: () => { $jq.fn.extend({ insertAtCaret: function (myValue) { var $t = $jq(this)[0]; if (document.selection) { this.focus(); var sel = document.selection.createRange(); sel.text = myValue; this.focus(); } else if ($t.selectionStart || $t.selectionStart == "0") { var startPos = $t.selectionStart; var endPos = $t.selectionEnd; var scrollTop = $t.scrollTop; $t.value = $t.value.substring(0, startPos) + myValue + $t.value.substring(endPos, $t.value.length); this.focus(); $t.selectionStart = startPos + myValue.length; $t.selectionEnd = startPos + myValue.length; $t.scrollTop = scrollTop; } else { this.value += myValue; this.focus(); } }, selectRange: function (start, end) { if (end === undefined) { end = start; } return this.each(function () { if ("selectionStart" in this) { this.selectionStart = start; this.selectionEnd = end; } else if (this.setSelectionRange) { this.setSelectionRange(start, end); } else if (this.createTextRange) { var range = this.createTextRange(); range.collapse(true); range.moveEnd("character", end); range.moveStart("character", start); range.select(); } }); }, getCursorPosition: function () { var el = $jq(this)[0]; var pos = 0; if ("selectionStart" in el) { pos = el.selectionStart; } else if ("selection" in document) { el.focus(); var Sel = document.selection.createRange(); var SelLength = document.selection.createRange().text.length; Sel.moveStart("character", -el.value.length); pos = Sel.text.length - SelLength; } return pos; }, moveCursorInCenterByText: function (leftTextFlag, rightTextFlag) { var el = $jq(this)[0]; var el_text = el.value; for (let i = el.selectionStart - 1; i > 0; i--) { let LText = el_text[i - 1]; let currentText = el_text[i]; if (LText == leftTextFlag && currentText == rightTextFlag) { this.selectRange(i); break; } } }, moveCursorToCenterByTextWithLeft: function (leftMatchText, _length_) { var el = $jq(this)[0]; var el_text = el.value; for (let index = el.selectionStart - 1; index > 0; index--) { let lTexts = el_text.substring(index - _length_, index); if (lTexts == leftMatchText) { this.selectRange(index); break; } } }, moveCursorToCenterByTextWithRight: function ( rightMatchText, _length_ ) { var el = $jq(this)[0]; var el_text = el.value; for (let i = el.selectionStart - 1; i > 0; i--) { let rTexts = el_text.substring(i, i + _length_); if (rTexts == rightMatchText) { this.selectRange(i + _length_); break; } } }, }); }, }, /** * 修复图片宽度 */ recoveryIMGWidth() { if (!DOM_CONFIG.methodRunCheck([DOM_CONFIG.urlRegexp.forumPost], "v16")) { return; } GM_addStyle(` .comiis_messages img{ max-width: 100% !important; } `); }, /** * 移除帖子内的字体style */ removeForumPostFontStyle() { if (!DOM_CONFIG.methodRunCheck([DOM_CONFIG.urlRegexp.forumPost], "v1")) { return; } if ($jq(".comiis_a.comiis_message_table").eq(0).html()) { $jq(".comiis_a.comiis_message_table") .eq(0) .html( $jq(".comiis_a.comiis_message_table") .eq(0) .html() .replace(DOM_CONFIG.urlRegexp.fontSpecial, "") ); } }, /** * 修复搜索的清空按钮 */ repairClearSearchInput() { if (!DOM_CONFIG.methodRunCheck([DOM_CONFIG.urlRegexp.searchUrl], "v36")) { return; } let $search_input = $jq(".ssclose.bg_e.f_e"); if ($search_input) { $search_input.click(function (event) { utils.preventEvent(event); $jq("#scform_srchtxt").val(""); }); } else { console.log("搜索界面: 获取清空按钮失败"); } }, /** * 修复评论区打赏评论因为文字或打赏人数评论太多导致高度显示不出来问题 */ repairRecommendRewardHeight() { if (window.location.href.match(DOM_CONFIG.urlRegexp.forumPost)) { GM_addStyle(` .comiis_view_lcrate li p{ height: auto !important; } `); } }, /** * 修复无法正确进入别人的空间 */ repairUnableToEnterOtherSpaceCorrectly() { if (!GM_getValue("v37")) { return; } if (window.location.href.match(DOM_CONFIG.urlRegexp.homeUrlBrief)) { let href_params = window.location.href.match(/home.php\?(.+)/gi); href_params = href_params[href_params.length - 1]; let params_split = href_params.split("&"); if ( params_split.length == 2 && href_params.indexOf("uid=") != -1 && href_params.indexOf("mod=space") != -1 ) { window.location.href = window.location.href + "&do=profile"; } } if (window.location.href.match(DOM_CONFIG.urlRegexp.homeUrlWithAt)) { let href_params = window.location.href.match(/space-uid-(.+).html/i); href_params = href_params[href_params.length - 1]; window.location.href = `https://bbs.binmt.cc/home.php?mod=space&uid=${href_params}&do=profile`; } }, /** * 搜索历史 */ async searchHistory() { if (!DOM_CONFIG.methodRunCheck([DOM_CONFIG.urlRegexp.searchUrl], "v19")) { return; } class searchSelect { constructor(config) { this.parentDOM = config.parentDOM ? config.parentDOM : null; this.list = this.arrayDistinct( config.list ? config.list : [] ); /* 用于搜索的数组 */ this.showList = this.list.length ? this.list : []; /* 用于显示在界面上的数组 */ this.inputValueChangeEvent = config.inputValueChangeEvent ? config.inputValueChangeEvent : () => { return []; }; this.css = { falInDuration: config?.css?.falInDuration ? config?.css?.falInDuration : 0.5, falInTiming: config?.css?.falInTiming ? config?.css?.falInTiming : "linear", falOutDuration: config?.css?.falOutDuration ? config?.css?.falOutDuration : 0.5, falOutTiming: config?.css?.falOutTiming ? config?.css?.falOutTiming : "linear", PaddingTop: config?.css?.PaddingTop ? config?.css?.PaddingTop : 8 /* 选择框距离输入框距离 */, }; this.searchSelectClassName = config.searchSelectClassName ? config.searchSelectClassName : "WhiteSevsSearchSelect"; /* 可修改div */ this.searchSelectHintClassName = config.searchSelectHintClassName ? config.searchSelectHintClassName : "whiteSevSearchHint"; /* 可修改ul */ this.searchSelectHTMLNoData = config.searchSelectHTMLNoData ? `
  • ${config.searchSelectHTMLNoData}
  • ` : '
  • 暂无其它数据
  • '; this.searchSelectHTML = ``; this.searchSelectDeleteItemHTML = ` `; this.searchSelectDeleteItemClicked = false; this.searchSelectCss = ``; if ( document.querySelector(`.${this.searchSelectClassName}`) == null ) { document.body.appendChild( this.parseTextToDOM(this.searchSelectHTML) ); document.body.appendChild( this.parseTextToDOM(this.searchSelectCss) ); } this.setParentEvent(); this.setItemEvent(); if (this.showList.length !== 0) { this.update(this.showList); } } parseTextToDOM(arg) { arg = arg .replace(/^[\n|\s]*/g, "") .replace(/[\n|\s]*$/g, ""); /* 去除前后的换行和空格 */ var objE = document.createElement("div"); objE.innerHTML = arg; var result = objE.children.length == 1 ? objE.children[0] : objE.children; return result; } addSearching() { document .querySelector(`ul.${this.searchSelectHintClassName}`) .appendChild( this.parseTextToDOM(`
  • 正在搜索中...
  • `) ); } removeSearching() { document .querySelector(`ul.${this.searchSelectHintClassName} .searching`) ?.remove(); } update(data) { /* 更新页面显示的搜索结果 */ if (!(data instanceof Array)) { console.log(data); throw "传入的数据不是数组"; } this.showList = this.arrayDistinct(data); document .querySelectorAll(`ul.${this.searchSelectHintClassName} li`) .forEach((item) => { item?.remove(); }); let that = this; var parentUlDOM = document.querySelector( `ul.${this.searchSelectHintClassName}` ); if (this.showList.length === 0) { this.clear(); if (this.parentDOM.value === "") { document .querySelectorAll(`ul.${this.searchSelectHintClassName} li`) .forEach((item) => { item?.remove(); }); this.list.forEach((item, index) => { parentUlDOM.appendChild( this.parseTextToDOM( `
  • ${item}${that.searchSelectDeleteItemHTML}
  • ` ) ); }); this.setItemEvent(); } else { this.parentDOM.dispatchEvent(new Event("focus")); } } else { this.showList.forEach((item, index) => { parentUlDOM.appendChild( this.parseTextToDOM( `
  • ${item}${that.searchSelectDeleteItemHTML}
  • ` ) ); }); this.setItemEvent(); } } arrayDistinct(data) { /* 数组去重 */ var result = []; data = new Set(data); for (let item of data.values()) { result = [item, ...result]; } return result; } clear() { this.showList = []; document .querySelectorAll(`ul.${this.searchSelectHintClassName} li`) .forEach((item) => { item?.remove(); }); document .querySelector(`ul.${this.searchSelectHintClassName}`) ?.appendChild(this.parseTextToDOM(this.searchSelectHTMLNoData)); } hide() { document .querySelector(`div.${this.searchSelectClassName}`) ?.setAttribute("style", "display: none;"); } show() { document .querySelector(`div.${this.searchSelectClassName}`) ?.removeAttribute("style"); } setParentValue(value) { this.parentDOM.value = value; } setParentEvent() { let that = this; function _focus_event_(event) { document .querySelector(`div.${that.searchSelectClassName}`) .setAttribute( "style", ` -moz-animation: searchSelectFalIn ${that.css.falInDuration}s 1 ${that.css.falInTiming}; -webkit-animation: searchSelectFalIn ${that.css.falInDuration}s 1 ${that.css.falInTiming}; -o-animation: searchSelectFalIn ${that.css.falInDuration}s 1 ${that.css.falInTiming}; -ms-animation: searchSelectFalIn ${that.css.falInDuration}s 1 ${that.css.falInTiming}; ` ); } function _blur_event_(event) { setTimeout(() => { if (that.searchSelectDeleteItemClicked) { return; } if ( getComputedStyle( document.querySelector(`div.${that.searchSelectClassName}`) ).display === "none" ) { return; } document .querySelector(`div.${that.searchSelectClassName}`) .setAttribute( "style", ` -moz-animation: searchSelectFalOut ${that.falOutDuration}s 1 ${that.falOutTiming}; -webkit-animation: searchSelectFalOut ${that.falOutDuration}s 1 ${that.falOutTiming}; -o-animation: searchSelectFalOut ${that.falOutDuration}s 1 ${that.falOutTiming}; -ms-animation: searchSelectFalOut ${that.falOutDuration}s 1 ${that.falOutTiming}; ` ); setTimeout(() => { document .querySelector(`div.${that.searchSelectClassName}`) .setAttribute("style", "display:none;"); }, that.falOutDuration * 1000); }, 100); } async function _propertychange_event_(event) { that.parentDOM.dispatchEvent(new Event("focus")); var getListResult = await that.getList(event.target.value); that.update(getListResult); } this.parentDOM?.setAttribute( "autocomplete", "off" ); /* 禁用输入框自动提示 */ this.parentDOM.addEventListener( "focus", function (event) { _focus_event_(event); }, true ); this.parentDOM.addEventListener( "click", function (event) { event.target.dispatchEvent(new Event("focus")); }, true ); this.parentDOM.addEventListener( "blur", function (event) { _blur_event_(event); }, false ); this.parentDOM.addEventListener( "input", function (event) { _propertychange_event_(event); }, true ); document.addEventListener("click", function () { var checkDOM = document.querySelector( "ul." + that.searchSelectHintClassName ); var mouseClickPosX = Number( window.event.clientX ); /* 鼠标相对屏幕横坐标 */ var mouseClickPosY = Number( window.event.clientY ); /* 鼠标相对屏幕纵坐标 */ var elementPosXLeft = Number( checkDOM.getBoundingClientRect().left ); /* 要检测的元素的相对屏幕的横坐标最左边 */ var elementPosXRight = Number( checkDOM.getBoundingClientRect().right ); /* 要检测的元素的相对屏幕的横坐标最右边 */ var elementPosYTop = Number( checkDOM.getBoundingClientRect().top ); /* 要检测的元素的相对屏幕的纵坐标最上边 */ var elementPosYBottom = Number( checkDOM.getBoundingClientRect().bottom ); /* 要检测的元素的相对屏幕的纵坐标最下边 */ if ( !( mouseClickPosX >= elementPosXLeft && mouseClickPosX <= elementPosXRight && mouseClickPosY >= elementPosYTop && mouseClickPosY <= elementPosYBottom ) && !( checkDOM.innerHTML.indexOf(window.event.target.innerHTML) !== -1 ) ) { that.searchSelectDeleteItemClicked = false; that.parentDOM.dispatchEvent(new Event("blur")); } }); } setItemEvent() { let that = this; document .querySelectorAll( `div.${this.searchSelectClassName} ul.${this.searchSelectHintClassName} li` ) .forEach((item, index) => { ((item2) => { item2.addEventListener( "click", function (event) { utils.preventEvent(event); that.searchSelectDeleteItemClicked = false; that.parentDOM.dispatchEvent(new Event("focus")); if (event.target.localName === "li") { that.parentDOM.value = this.innerText; that.parentDOM.dispatchEvent(new Event("blur")); } else { that.searchSelectDeleteItemClicked = true; var dataId = parseInt(item2.getAttribute("data-id")); console.log("删除 " + that.showList[dataId]); that.list.forEach((item, index) => { if (item === this.innerText) { that.list.splice(index, 1); return; } }); that.showList.splice(dataId, 1); item2.remove(); document .querySelectorAll( `ul.${that.searchSelectHintClassName} li` ) .forEach((item, index) => { item.setAttribute("data-id", index); }); that.list = that.list; that.showList = that.showList; GM_setValue("search_history", that.list); if (that.list.length === 0) { that.clear(); } } }, true ); })(item, index); }); } getList(text) { var event = {}; var that = this; event.userInputText = text; event.target = this.parentDOM; event.list = this.list; event.showList = this.showList; this.addSearching(); return new Promise((resolve) => { var result = that.inputValueChangeEvent(event); if (this.parentDOM.value !== "" && result.length == 0) { this.parentDOM.dispatchEvent(new Event("focus")); } that.removeSearching(); resolve(result); }); } } GM_addStyle(` #comiis_search_noe{ display: none !important; } #comiis_search_two{ display: block !important; } `); var searchHistoryList = await GM_getValue("search_history", []); new searchSelect({ parentDOM: document.querySelector("#scform_srchtxt"), list: searchHistoryList, inputValueChangeEvent: (event) => { var result = []; event.userInputText = event.userInputText.trim(); if (event.userInputText == "") { return result; } event.list.forEach((item) => { if ( item.match( event.userInputText.replace( /[\-\/\\\^\$\*\+\?\.\(\)\|\[\]\{\}]/g, "\\$&" ) ) ) { result = [item, ...result]; } }); return result; }, }); function search_event() { /* 搜索历史事件 */ /* 搜索界面增加关闭按钮事件,清空input内容 */ /* 点击搜索保存搜索记录 */ $jq("#scform_submit").click(function () { let getsearchtext = $jq("#scform_srchtxt").val(); if (getsearchtext != null && getsearchtext != "") { let search_history_array = new Array(getsearchtext); let has_history = GM_getValue("search_history"); if (has_history != null) { if ($jq.inArray(getsearchtext, has_history) != -1) { console.log("已有该搜索历史记录"); search_history_array = has_history; } else { console.log("无该记录,追加"); search_history_array = search_history_array.concat(has_history); } } else { console.log("空记录,添加"); } GM_setValue("search_history", search_history_array); } }); } function add_clear_history() { /* 搜索界面添加清理历史记录和历史记录个数 */ let search_history_list = GM_getValue("search_history"); let search_history_nums = 0; if (search_history_list != null) { search_history_nums = search_history_list.length; } let clear_history_innerHTML = `
    搜索记录个数: ` + search_history_nums + `
    `; let insertdom = $jq( ".comiis_p12.f14.bg_f.f_c.b_b.cl,.comiis_tagtit.b_b.f_c" ); insertdom.before(clear_history_innerHTML); $jq(".btn_clear_search_history").click(function () { GM_deleteValue("search_history"); window.location.reload(); }); } search_event(); add_clear_history(); }, /** * 在发帖|编辑帖子时选择发帖板块 */ selectPostingSection() { if ( !DOM_CONFIG.methodRunCheck([ DOM_CONFIG.urlRegexp.postForum, DOM_CONFIG.urlRegexp.editForum, ]) ) { return; } GM_addStyle( `#select-post-section{height:28px;width:160px;line-height:28px;border:1px solid #ececec;background:url(w.png) no-repeat;background-position:95% 50%;-webkit-appearance:none;appearance:none;-moz-appearance:none}` ); let section_dict = { 2: "版本发布", 37: "插件交流", 38: "建议反馈", 41: "逆向交流", 39: "玩机交流", 42: "编程开发", 40: "求助问答", 44: "综合交流", 50: "休闲灌水", 46: "官方公告", 53: "申诉举报", 92: "站务专区", }; $jq( ".comiis_post_from .comiis_wzpost.comiis_input_style .comiis_styli:contains('标题')" ).before( $jq(`
  • 板块
  • `) ); let selectNode = $jq(`#select-post-section`); let currentSection = window.location.search.match(/fid=([0-9]+)/); currentSection = currentSection[currentSection.length - 1]; if (window.location.href.match(DOM_CONFIG.urlRegexp.postForum)) { /* 发帖 */ console.log("发帖"); selectNode.on("change", function () { let obj = $jq(this); let fid = obj.val(); let postSection = `forum.php?mod=post&action=newthread&fid=${fid}&extra=&topicsubmit=yes&mobile=2`; console.log(`修改发帖板块: ${section_dict[fid]} ${postSection}`); let classifyClassNameDict = { 求助问答: { className: "gm_user_select_help", optionHTML: ` `, }, 建议反馈: { className: "gm_user_select_feedback", optionHTML: ` `, }, 站务专区: { className: "gm_user_select_depot", optionHTML: ` `, }, }; if (classifyClassNameDict[section_dict[fid]]) { if ($jq(".comiis_post_from .styli_tit:contains('分类')").length) { $jq(".comiis_post_from .styli_tit:contains('分类')") .parent() .remove(); } $jq(".comiis_stylino.comiis_needmessage").before( $jq(`
  • 分类
  • `) ); } else { Object.keys(classifyClassNameDict).forEach((key) => { $jq( ".comiis_post_from ." + classifyClassNameDict[key]["className"] ).remove(); }); } $jq("#postform").attr("action", postSection); }); } else { selectNode.attr("disabled", true); } selectNode.val(currentSection).trigger("change"); }, /** * 设置动态头像 * 感谢提供思路 https://greasyfork.org/zh-CN/scripts/11969-discuz论坛头像上传助手 */ setDynamicAvatar() { if ( !DOM_CONFIG.methodRunCheck([DOM_CONFIG.urlRegexp.dataSettingUrl], "v51") ) { return; } let formhash = $jq(".sidenv_exit a:nth-child(1)") .attr("href") .match(/formhash=([0-9a-zA-Z]+)/); let uid = $jq(".sidenv_exit a:nth-child(2)") .attr("href") .match(/uid=([0-9]+)/); /* 获取UID */ let avatarInfo = { maxSize: 2097152 /* 图片文件最大大小 */, big: { width: 200, height: 250, status: false, }, medium: { width: 120, height: 120, status: false, }, small: { width: 48, height: 48, status: false, }, }; formhash = formhash[formhash.length - 1]; uid = uid[uid.length - 1]; let dynamicAvater = $jq(`
    修改动态头像
    `); function getStatus() { /* 获取变量状态 */ return ( avatarInfo.big.status && avatarInfo.medium.status && avatarInfo.small.status ); } function setStatus(key, value) { /* 设置变量状态 */ if (key === "comiis_file_dynamic_avater_big") { avatarInfo.big.status = value; } else if (key === "comiis_file_dynamic_avater_medium") { avatarInfo.medium.status = value; } else { avatarInfo.small.status = value; } } function getPCUploadNewAvater() { return new Promise((resolve) => { GM_xmlhttpRequest({ url: "https://bbs.binmt.cc/home.php?mod=spacecp&ac=avatar", method: "GET", timeout: 5000, headers: { "User-Agent": utils.getRandomPCUA(), }, onload: function (response) { resolve(response.responseText); }, onerror: function () { popups.toast("网络异常,请重新获取"); resolve(""); }, ontimeout: () => { popups.toast("请求超时"); resolve(""); }, }); }); } function changeCheckFileEvent( elementQuery, maxWidth, maxHeight, maxSize ) { /* 检查上传的文件是否符合,大小,尺寸 */ $jq(elementQuery).on("change", function () { let uploadImageFile = this.files[0]; let fileSize = uploadImageFile.size; let tmpImage = new Image(); let reader = new FileReader(); reader.readAsDataURL(uploadImageFile); reader.onload = function (response) { tmpImage.src = response.target.result; tmpImage.onload = function () { if (this.width > maxWidth || this.height > maxHeight) { $jq(elementQuery).val(""); popups.toast({ text: `图片尺寸超出,当前宽:${this.width} 高:${this.height}`, delayTime: 4000, }); return; } if (fileSize > maxSize) { $jq(elementQuery).val(""); popups.toast({ text: `图片大小(最大${maxSize})超出,当前大小:${fileSize}`, delayTime: 4000, }); return; } }; }; }); } $jq(".comiis_edit_avatar").after(dynamicAvater); dynamicAvater.on("click", () => { popups.confirm({ text: `

    修改动态头像

    1. 桌面端头像: ${avatarInfo.big.width}×${avatarInfo.big.height}

    🤡请先上传图片

    2. 移动端头像: ${avatarInfo.medium.width}×${avatarInfo.medium.height}

    🤡请先上传图片

    3. 桌面端右上角小头像: ${avatarInfo.small.width}×${avatarInfo.small.height}

    🤡请先上传图片

    `, mask: true, only: true, ok: { text: "上传", callback: async () => { if (!getStatus()) { popups.toast("图片校验不通过"); return; } popups.loadingMask(); popups.toast("正在处理数据中..."); let baseBig = await utils.parseFileToBase64( $jq("#comiis_file_dynamic_avater_big").prop("files")[0] ); let baseMedium = await utils.parseFileToBase64( $jq("#comiis_file_dynamic_avater_medium").prop("files")[0] ); let baseSmall = await utils.parseFileToBase64( $jq("#comiis_file_dynamic_avater_small").prop("files")[0] ); let base64Arr = [baseBig, baseMedium, baseSmall]; const dataArr = base64Arr.map((str) => str.substr(str.indexOf(",") + 1) ); /* 拿到3个头像的Base64字符串 */ let data_resp = await getPCUploadNewAvater(); if (data_resp == "") { popups.toast("获取PC数据失败"); popups.closeMask(); return; } let data = data_resp.match(/var[\s]*data[\s]*=[\s]*"(.+?)"/); if (data == null || data.length != 2) { popups.toast("获取变量-data失败"); popups.closeMask(); return; } data = data[data.length - 1]; let data_split = data.split(","); let uploadUrl = data_split[data_split.indexOf("src") + 1].replace( "images/camera.swf?inajax=1", "index.php?m=user&a=rectavatar&base64=yes" ); let formData = new FormData(); formData.append("Filedata", ""); formData.append("avatar1", dataArr[0]); formData.append("avatar2", dataArr[1]); formData.append("avatar3", dataArr[2]); formData.append("formhash", formhash); GM_xmlhttpRequest({ url: uploadUrl, method: "POST", data: formData, headers: { Origin: "https://bbs.binmt.cc", Referer: "https://bbs.binmt.cc/home.php?mod=spacecp&ac=avatar", Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9", "User-Agent": utils.getRandomPCUA(), }, onload: function (response) { let text = response.responseText; if ( text.indexOf("window.parent.postMessage('success','*')") != -1 ) { popups.toast("上传成功"); popups.closeConfirm(); setTimeout(() => { window.location.reload(); }, 1500); } else { popups.toast(text); } }, onerror: function () { popups.toast("网络异常,请重新获取"); }, }); }, }, }); }); $jq(document).on( "change", "#popups-confirm input[type='file']", function () { let fileObj = $jq(this); if (fileObj.prop("files").length == 0) { return; } let statusObj = fileObj.parent().find(".status"); let maxWidth = parseInt(fileObj.attr("data-maxwidth")); let maxHeight = parseInt(fileObj.attr("data-maxheight")); statusObj.text("🤡获取文件信息中..."); let uploadImageFile = fileObj.prop("files")[0]; let fileSize = uploadImageFile.size; let tmpImage = new Image(); let reader = new FileReader(); reader.readAsDataURL(uploadImageFile); reader.onload = function (response) { tmpImage.src = response.target.result; tmpImage.onload = function () { if (this.width > maxWidth || this.height > maxHeight) { /* 判断尺寸大小 */ setStatus(fileObj.attr("id"), false); fileObj.val(""); statusObj.text( `🤡校验失败,图片尺寸不符合 宽:${this.width} 高:${this.height}` ); return; } if (fileSize > avatarInfo.maxSize) { setStatus(fileObj.attr("id"), false); fileObj.val(""); statusObj.text("🤡校验失败,图片大小不符合 " + fileSize); return; } setStatus(fileObj.attr("id"), true); statusObj.text( `🤣 通过 宽:${this.width} 高:${this.height} 大小(byte):${fileSize}` ); }; }; } ); changeCheckFileEvent( "#comiis_file_dynamic_avater_big", avatarInfo.big.width, avatarInfo.big.height, avatarInfo.maxSize ); changeCheckFileEvent( "#comiis_file_dynamic_avater_medium", avatarInfo.medium.width, avatarInfo.medium.height, avatarInfo.maxSize ); changeCheckFileEvent( "#comiis_file_dynamic_avater_small", avatarInfo.small.width, avatarInfo.small.height, avatarInfo.maxSize ); }, /** * 导读新增显示最新帖子 */ showLatestPostForum() { if ( !DOM_CONFIG.methodRunCheck([DOM_CONFIG.urlRegexp.navigationUrl], "v53") ) { return; } if ( window.location.href.match( /bbs.binmt.cc\/forum.php\?mod=guide&view=hot/g ) ) { return; } /** * 获取轮播的最新的帖子 * @returns {Promise} */ function getLatestPostForum() { return new Promise((resolve) => { GM_xmlhttpRequest({ url: "https://bbs.binmt.cc/forum.php?mod=guide&view=hot", method: "GET", timeout: 8000, async: false, responseType: "html", headers: { Referer: "https://bbs.binmt.cc/forum.php?mod=guide&view=newthread&index=1", Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7", "User-Agent": utils.getRandomAndroidUA(), }, onload: function (response) { console.log(response); if (response.status !== 200) { popups.toast("获取轮播失败 状态码:" + response.status); resolve([]); return; } if ( response.responseText.indexOf( '' ) !== -1 ) { popups.toast("获取轮播失败 未知的/_guard/auto.js文件"); resolve([]); return; } var respHTML = utils.parseFromString(response.responseText); var postForumList = respHTML.querySelectorAll( 'div.comiis_mh_kxtxt div[id*="comiis_mh_kxtxt"] ul' ); if (postForumList.length === 0) { popups.toast("获取轮播失败"); resolve([]); } else { var result = []; postForumList[postForumList.length - 1] .querySelectorAll("a") .forEach((item) => { result = [ { href: item.getAttribute("href"), title: item.getAttribute("title"), }, ...result, ]; }); resolve(result); } }, onerror: function (response) { console.log(response); popups.toast("网络异常,获取轮播失败"); resolve([]); }, ontimeout: () => { popups.toast("请求超时"); resolve([]); }, }); }); } getLatestPostForum().then((result) => { if (result.length) { GM_addStyle(` div.comiis_mh_kxtxt_owm{ margin-top: 10px; } div.comiis_mh_kxtxt_owm li{ height: 30px; width: 100%; display: flex; align-items: center; } div.comiis_mh_kxtxt_owm span{ background: #FF705E; color: #fff; float: left; height: 18px; line-height: 18px; padding: 0 3px; margin-top: 2px; margin-right: 10px; overflow: hidden; border-radius: 2px; margin-left: 10px; } div.comiis_mh_kxtxt_owm a{ display: block; font-size: 14px; font-weight: 400; height: 22px; line-height: 22px; overflow: hidden; min-width: 100px; max-width: 80%; text-overflow: ellipsis; white-space: nowrap; margin-right: 10px; } `); var latestPostForumHTML = ""; utils.sortListByProperty( result, (item) => { var forumPostNum = item["href"].match(/thread-(.+?)-/i); forumPostNum = forumPostNum[forumPostNum.length - 1]; forumPostNum = parseInt(forumPostNum); return forumPostNum; }, true ); console.log("导读内容", result); result.forEach((item) => { latestPostForumHTML += `
  • 新帖 ${item.title}
  • `; }); $jq(".comiis_forumlist.comiis_xznlist").before( $jq( `
      ${latestPostForumHTML}
    ` ) ); } }); }, /** * 显示签到的最先几个人,最多10个,和顶部的今日签到之星 */ showSignInRanking() { if (!DOM_CONFIG.methodRunCheck([DOM_CONFIG.urlRegexp.kMiSignSign])) { return; } let today_ranking_ele = document.querySelector( ".comiis_topnv .comiis_flex .flex" ); today_ranking_ele.after( $jq( `
  • 今日最先
  • ` )[0] ); let getMaxPage = (urlextra) => { return new Promise((resolve) => { GM_xmlhttpRequest({ url: `https://bbs.binmt.cc/k_misign-sign.html?operation=${urlextra}`, method: "GET", async: false, responseType: "html", timeout: 5000, headers: { "User-Agent": utils.getRandomPCUA(), }, onload: function (response) { let last_page = $jq(response.responseText).find( "#J_list_detail .pg span" ); if ( last_page.length && typeof last_page[0].title != "undefined" ) { let last_page_match = last_page[0].title.match(/([0-9]+)/); if (last_page_match.length == 2) { resolve(last_page_match[last_page_match.length - 1]); } else { popups.toast("获取页失败"); resolve(0); } } else { popups.toast("请求最先签到的页失败"); resolve(0); } }, onerror: function (response) { console.log(response); popups.toast("网络异常,请重新获取"); resolve(0); }, ontimeout: () => { popups.toast("请求超时"); resolve(0); }, }); }); }; let getPagePeople = (page) => { return new Promise((resolve) => { GM_xmlhttpRequest({ url: `https://bbs.binmt.cc/k_misign-sign.html?operation=list&op=&page=${page}`, method: "GET", async: false, timeout: 5000, responseType: "html", headers: { "User-Agent": utils.getRandomPCUA(), }, onload: function (response) { let peoples = $jq(response.responseText).find( "#J_list_detail tbody tr" ); let ret_array = []; if ( peoples.length == 2 && peoples[0].textContent.indexOf("暂无内容") != -1 ) { resolve(ret_array); return; } for (let i = 1; i <= peoples.length - 2; i++) { let people = peoples[i]; let ret_json = {}; let user_name = people.children[0].getElementsByTagName("a")[0].textContent; let space_url = people.children[0].getElementsByTagName("a")[0].href; let uid = space_url.match(/space-uid-([0-9]*)/)[1]; let sign_all_days = people.children[1].textContent; let sign_month_days = people.children[2].textContent; let sign_time = people.children[3].textContent; let sign_reward = people.children[5].textContent; ret_json["user"] = user_name; ret_json["uid"] = uid; ret_json["avatar"] = DOM_CONFIG.getAvatar(uid, "small"); ret_json["days"] = sign_all_days; ret_json["monthDays"] = sign_month_days; ret_json["time"] = sign_time; ret_json["reward"] = sign_reward; ret_array = ret_array.concat(ret_json); } resolve(ret_array); }, onerror: function (response) { console.log(response); resolve({}); }, ontimeout: () => { popups.toast("请求超时"); resolve({}); }, }); }); }; function changeRankList(data, listtype) { $jq("#ranklist").html(data); $jq("#ranklist").attr("listtype", listtype); } ajaxlist = async (listtype) => { listtype = listtype; if (listtype == "today") { loadingdelay = false; urlextra = "list&op=today"; } else if (listtype == "month") { loadingdelay = false; urlextra = "list&op=month"; } else if (listtype == "zong") { loadingdelay = false; urlextra = "list&op=zong"; } else if (listtype == "calendar") { loadingdelay = true; urlextra = "calendar"; } else { loadingdelay = false; urlextra = "list"; } /* alert(loadingdelay); */ if (listtype == "todayLatest") { loadingdelay = false; urlextra = "list&op=&page=0"; let maxPage = await getMaxPage(urlextra); if (maxPage == 0) { return; } let latestPeople = await getPagePeople(maxPage); latestPeople.reverse(); if (latestPeople.length < 10) { let latestPeople_2 = await getPagePeople(maxPage - 1); latestPeople_2.reverse(); latestPeople = latestPeople.concat(latestPeople_2); latestPeople.reverse(); } let peopleHTML = ""; latestPeople.reverse(); console.log(latestPeople); latestPeople.forEach((people) => { peopleHTML = peopleHTML + `

    ${people["user"]} ${people["time"]} 总天数 ${people["days"]}天

    月天数 ${people["monthDays"]} 天,上次奖励 ${people["reward"]}

    `; }); let latestHTML = `
  • ` + peopleHTML + `
    `; changeRankList(latestHTML, listtype); } else { $jq.ajax({ type: "GET", url: `plugin.php?id=k_misign:sign&operation=${urlextra}`, async: false, dataType: "html", success: function (response) { /* console.log(data); */ response = response.replace( `今日排行`, `今日排行
  • 今日最先
  • ` ); changeRankList(response, listtype); }, complete: function (XHR, TS) { XHR = null; }, }); } }; }, /** * 显示今日之星,在签到页上 */ showTodayStar() { if ( !DOM_CONFIG.methodRunCheck([DOM_CONFIG.urlRegexp.kMiSignSign], "v33") ) { return; } let todayStarParent = $jq(".pg_k_misign .comiis_qdinfo"); let todayStar = document.createElement("ul"); GM_xmlhttpRequest({ url: "https://bbs.binmt.cc/k_misign-sign.html", method: "GET", async: false, timeout: 5000, headers: { "User-Agent": utils.getRandomPCUA(), }, onload: (response) => { let html = $jq(response.responseText); let todatastarele = html.find("#pt span.xg1"); if (!todatastarele.length) { return; } let todaypeople = todatastarele[0].textContent.replace( "今日签到之星:", "" ); todayStar.innerHTML = '
  • 今日签到之星' + todaypeople + "
  • "; let comiis_space_box_height = getComputedStyle( $jq(".comiis_space_box")[0], null )["height"].replace("px", ""); let comiis_space_box_padding_bottom = getComputedStyle( $jq(".comiis_space_box")[0], null )["padding-bottom"].replace("px", ""); comiis_space_box_height = parseInt(comiis_space_box_height); comiis_space_box_padding_bottom = parseInt( comiis_space_box_padding_bottom ); let total_height = comiis_space_box_height + comiis_space_box_padding_bottom + 50; GM_addStyle(` .comiis_space_box{ height: ${total_height}px; background-size: 100% 100%; } .pg_k_misign .comiis_qdinfo{ height: 110px !important; }`); todayStarParent.append(todayStar); }, onerror: (response) => { console.log(response); console.log("请求今日之星失败"); popups.toast("请求今日之星失败"); }, ontimeout: () => { popups.toast("请求今日之星超时"); console.log("请求超时"); }, }); }, /** * 显示空间-帖子-具体回复 */ async showSpaceContreteReply() { if (!DOM_CONFIG.methodRunCheck([DOM_CONFIG.urlRegexp.spacePost], "v52")) { return; } GM_addStyle(` div.contrete-reply{padding:5px 10px;border-top:1px solid #f3f3f3} div.contrete-reply a{margin:0 10px} `); /** * 获取PC端的回复内容 * @returns {[Array]} */ function getPCReply() { return new Promise((resolve) => { GM_xmlhttpRequest({ url: window.location.href, method: "GET", async: false, timeout: 5000, headers: { "User-Agent": utils.getRandomPCUA(), }, onload: (response) => { let pageHTML = $jq(response.responseText); let forum = pageHTML.find("#delform tr.bw0_all+tr"); let resultList = []; Array.from(forum).forEach((item) => { let replyData = []; let tagTDNode = $jq($jq(item).find("td")); let tagTDValue = tagTDNode.html().replace(/^ /, ""); replyData = replyData.concat(tagTDValue); let nextHTML = $jq(item).next(); /* bw0_all是每个帖子的标志位 */ for ( let index = 0; index < pageHTML.find("#delform tr").length; index++ ) { if ( nextHTML.attr("class") === "bw0_all" || nextHTML.length === 0 ) { break; } let nextTdHTML = nextHTML.find("td"); let nextValue = nextTdHTML.html().replace(/^ /, ""); replyData = replyData.concat(nextValue); nextHTML = nextHTML.next(); } resultList.push(replyData); }); resolve(resultList); }, onerror: () => { console.error("网络异常,获取PC回复失败"); popups.toast("网络异常,获取PC回复失败"); resolve(null); }, ontimeout: () => { console.error("网络异常,获取PC回复失败"); popups.toast("请求超时,获取PC回复失败"); resolve(null); }, }); }); } /** * 获取当前页面所有帖子 * @returns {NodeList} */ function getForumList() { return utils.getNodeListValue( DOM_CONFIG.element.comiisForumList, DOM_CONFIG.element.comiisPostli, DOM_CONFIG.element.comiisMmlist ); } /** * 格式化一下获取的PC端的回复的内容 * @param {Array} dataList */ function formatPCReply(dataList) { let resultJSON = {}; dataList.forEach((item) => { let divItem = $jq(`
    ${item[0]}
    `); let url = divItem.find("a").prop("href"); let paramPtid = url.match(DOM_CONFIG.urlRegexp.forumPostParam_ptid); let paramPid = url.match(DOM_CONFIG.urlRegexp.forumPostParam_pid); if (!paramPtid) { popups.toast("获取ptid失败"); return; } if (!paramPid) { popups.toast("获取pid失败"); return; } paramPtid = paramPtid[paramPtid.length - 1]; paramPid = paramPid[paramPid.length - 1]; if (resultJSON[paramPtid]) { resultJSON[paramPtid]["data"] = [ ...resultJSON[paramPtid]["data"], ...item, ]; } else { resultJSON[paramPtid] = { ptid: paramPtid, pid: paramPid, data: item, }; } }); return resultJSON; } var pcReplyArray = await getPCReply(); if (pcReplyArray == null) { return; } var pcReplyJSON = formatPCReply(pcReplyArray); console.log(pcReplyJSON); let forumList = getForumList(); forumList.forEach((forumListItem, forumListItemIndex) => { /* 点赞按钮 */ let praiseNode = forumListItem.querySelector( ".comiis_xznalist_bottom a" ); let forumTid = praiseNode.getAttribute("tid"); if (!forumTid) { popups.toast("获取帖子tid失败"); console.error(forumListItem); return; } if (!pcReplyJSON[forumTid]) { return; } pcReplyJSON[forumTid]["data"].forEach((forumListReplyHTMLItem) => { $jq(forumListItem).append( $jq(`
    ${forumListReplyHTMLItem}
    `) ); }); }); }, /** * 注册设置菜单项 */ registerSettingView() { /** * 设置 脚本设置界面的事件 */ function setPageSettingViewEvent() { /** * 选项全选中 */ $jq(".NZ-MsgBox-alert .msgtitle").on("click", function () { let inputCheckList = document.querySelectorAll( ".whitesev-mt-setting-item input[type=checkbox]" ); let inputUnCheckedList = document.querySelectorAll( ".whitesev-mt-setting-item input[type=checkbox]:not(:checked)" ); if (inputUnCheckedList.length === 0) { /* 都已选中 */ inputCheckList.forEach((item) => item.click()); } else { /* 存在未选中的 */ inputUnCheckedList.forEach((item) => item.click()); } }); $jq(".whitesev-mt-setting-item input[type='checkbox']").each( (index, item) => { item = $jq(item); let dataKey = item.attr("data-key"); item.prop("checked", GM_getValue(dataKey, false)); } ); $jq(".whitesev-mt-setting-item input[type='checkbox']").on( "click", function () { let dataKey = $jq(this).attr("data-key"); GM_setValue(dataKey, this.checked); } ); let db = new utils.indexedDB("mt_reply_record", "input_text"); db.get("data").then((result) => { if (!result.success) { console.warn(result); return; } let settingNameDOM = document .querySelector( '.whitesev-mt-setting-checkbox input[data-key="v58"]' ) .closest(".whitesev-mt-setting-item") .querySelector(".whitesev-mt-setting-name"); settingNameDOM.innerHTML = settingNameDOM.innerHTML + `(${utils.getTextStorageSize( utils.mergeArrayToString(result.data) )})`; }); } /** * 设置 脚本设置界面的CSS */ function setPageSettingViewCSS() { /* checkbox美化 */ GM_addStyle(` .whitesev-mt-setting-checkbox .knobs,.whitesev-mt-setting-checkbox .layer{position:absolute;top:0;right:0;bottom:0;left:0} .whitesev-mt-setting-checkbox{position:relative;width:56px;height:28px;overflow:hidden} .whitesev-mt-setting-checkbox input[type=checkbox]{position:relative;width:100%;height:100%;padding:0;margin:0;opacity:0;cursor:pointer;z-index:3} .whitesev-mt-setting-checkbox .knobs{z-index:2} .whitesev-mt-setting-checkbox .layer{width:100%;background-color:#fcebeb;transition:.3s ease all;z-index:1} .whitesev-mt-setting-checkbox .knobs span,.whitesev-mt-setting-checkbox .knobs:before{position:relative;display:block;top:50%;left:30%;width:20%;height:auto;color:#fff;font-size:10px;font-weight:700;text-align:center;line-height:1;padding:9px 4px;transform:translate(-50%,-50%)} .whitesev-mt-setting-checkbox .knobs span{background-color:#f44336;border-radius:2px;transition:.3s ease all,left .3s cubic-bezier(.18,.89,.35,1.15);z-index:1} .whitesev-mt-setting-checkbox .knobs:before{transition:.3s ease all,left .5s cubic-bezier(.18,.89,.35,1.15);z-index:2} .whitesev-mt-setting-checkbox input[type=checkbox]:checked+.knobs span{left:70%;background-color:#03a9f4} .whitesev-mt-setting-checkbox input[type=checkbox]:checked~.layer{background-color:#ebf7fc}`); GM_addStyle(` .whitesev-mt-setting{height:400px;overflow-y:auto} .whitesev-mt-setting-item{width:100%;display:inline-flex;margin:15px 0;align-items:center;justify-content:space-between} .whitesev-mt-setting-name{margin-left:10px;max-width:70%} .whitesev-mt-setting-checkbox{margin-right:10px} `); } /** * 设置 脚本设置界面 */ function setPageSettingView() { GM_addStyle(` .NZ-MsgBox-alert .msgcontainer .msgtitle { text-align: center !important; }`); let settingView = $jq(`
  • MT论坛脚本设置
  • `); settingView.on("click", function () { $jq.NZ_MsgBox.alert({ title: "MT论坛脚本设置", content: `

    识别链接

    自动签到

    自动展开帖子

    自适应帖子内图片的宽度

    显示用户的UID

    显示搜索历史

    移除帖子字体效果

    移除评论区字体效果

    评论区点评按钮

    自动加载上一页评论

    自动加载下一页评论

    小黑屋

    今日签到之星

    修复搜索的清空按钮

    修复无法正确进入别人的空间

    聊天内图床

    付费主题白嫖提醒

    页面小窗浏览帖子

    代码块优化

    蓝奏云功能

    编辑器优化-快捷

    编辑器优化-完整

    上传动态头像

    空间-帖子-显示具体回复内容

    导读新增显示最新帖子

    帖子快照

    贴内图片查看优化

    在线用户查看

    附件点击提醒

    每7天清理回复框记录的数据

    自动加载上/下页评论时同步地址

    `, type: "", buttons: { confirm: { text: "好的" }, }, }); setPageSettingViewEvent(); }); $jq(".comiis_sidenv_box .sidenv_li .comiis_left_Touch.bdew").append( settingView ); } if (window.location.href.match(DOM_CONFIG.urlRegexp.bbs)) { setPageSettingView(); setPageSettingViewCSS(); } }, }; /** * 这是入口 */ const entrance = function () { if (!envIsMobile()) { console.log("PC端显示"); utils.tryCatch().run(pc.repairPCNoLoadResource); $jq(document).ready(function () { pc.main(); }); } else { console.log("移动端显示"); mobileBusiness.smallWindow.setMessageListener(); $jq(document).ready(function () { utils.tryCatch().run(mobile.registerSettingView); mobile.main(); }); } }; /** * 第一次使用该脚本的提示 */ const firstUseTip = function () { if (GM_getValue("firstUse", true) && envIsMobile()) { var tipImage = "https://www.helloimg.com/images/2023/01/04/oCgy7o.gif"; popups.confirm({ text: `

    如果您是第一次使用,请看演示GIF

    演示图-48MB`, cancel: { text: "不再提醒", callback: () => { GM_setValue("firstUse", false); popups.closeConfirm(); popups.closeMask(); }, }, }); } }; if (window !== top.window) { window.parent.postMessage("xtip interactive"); } let envCheckResult = envCheck(); if (envCheckResult) { $jq(document).ready(function () { entrance(); console.log(`执行完毕,耗时${Date.now() - DOM_CONFIG.gmRunStartTime}ms`); firstUseTip(); }); } })();