// ==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 = `
`;
} else {
bottomBtnHTML = `
`;
}
confirmHTML = `
`;
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(`
`)
);
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(
``
);
$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(``)[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(``)[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(``)[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: ``,
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["username"]}
${value["dateline"]}
${value["action"]}
到期: ${value["groupexpiry"]}
UID: ${value["uid"]}
${value["operator"]}
${value["reason"]}
`;
}
/**
* 获取小黑屋名单列表
* @param {String} cid 下一页的cid
*/
function getBlackList(cid = "") {
return new Promise(async (resolve) => {
popups.toast("正在获取小黑屋名单中...");
let result = await getBlackListPageInfoHTML(cid);
if (result === "" || result.startsWith("'
) !== -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(
``
)
);
}
});
},
/**
* 显示签到的最先几个人,最多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 =
`
`;
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: `
`,
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
`,
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();
});
}
})();