b-live-random-send-test

定时从设置的字幕中随机取出一条在B站直播间发送,需先登录B站账号

当前为 2024-10-07 提交的版本,查看 最新版本

此脚本不应直接安装。它是供其他脚本使用的外部库,要使用该库请加入元指令 // @require https://update.cn-greasyfork.org/scripts/447936/1460620/b-live-random-send-test.js

  1. // ==UserScript==
  2. // @version 1.7.2.12
  3. // ==/UserScript==
  4.  
  5.  
  6.  
  7. (function () {
  8. const blobURL = URL.createObjectURL(
  9. new Blob(
  10. [
  11. '(',
  12. function () {
  13. const ids = {};
  14. // 监听message 开始执行定时器或者销毁
  15. self.onmessage = (e) => {
  16. switch (e.data.command) {
  17. case 'interval:start': // 开启定时器
  18. const intervalId = setInterval(() => postMessage({
  19. message: 'interval:tick',
  20. id: e.data.id
  21. }), e.data.interval);
  22. // postMessage({ message: 'interval:started', id: e.data.id });
  23. ids[e.data.id] = intervalId;
  24. break;
  25. case 'interval:clear': // 销毁
  26. clearInterval(ids[e.data.id]);
  27. postMessage({ message: 'interval:cleared', id: e.data.id });
  28. delete ids[e.data.id];
  29. break;
  30. case 'timeout:start':
  31. const timeoutId = setTimeout(() => postMessage({
  32. message: 'timeout:tick',
  33. id: e.data.id
  34. }), e.data.timeout);
  35. // postMessage({ message: 'timeout:started', id: e.data.id });
  36. ids[e.data.id] = timeoutId;
  37. break;
  38. case 'timeout:clear':
  39. clearTimeout(ids[e.data.id]);
  40. postMessage({ message: 'timeout:cleared', id: e.data.id });
  41. delete ids[e.data.id];
  42. break;
  43. }
  44. };
  45. }.toString(),
  46. ')()',
  47. ],
  48. { type: 'application/javascript' },
  49. ),
  50. );
  51. const worker = new Worker(blobURL);
  52. URL.revokeObjectURL(blobURL); //用完释放URL对象
  53. const workerTimer = {
  54. id: 0,
  55. callbacks: {},
  56. setInterval: (cb, interval, context) => {
  57. const id = ++workerTimer.id;
  58. workerTimer.callbacks[id] = { fn: cb, context: context };
  59. worker.postMessage({ command: 'interval:start', interval: interval, id: id });
  60. return id;
  61. },
  62. setTimeout: (cb, timeout, context) => {
  63. const id = ++workerTimer.id;
  64. workerTimer.callbacks[id] = { fn: cb, context: context };
  65. worker.postMessage({ command: 'timeout:start', timeout: timeout, id: id });
  66. return id;
  67. },
  68.  
  69. // 监听worker 里面的定时器发送的message 然后执行回调函数
  70. onMessage: (e) => {
  71. switch (e.data.message) {
  72. case 'interval:tick':
  73. case 'timeout:tick':
  74. const callbackItem = workerTimer.callbacks[e.data.id];
  75. if (callbackItem && callbackItem.fn) {
  76. callbackItem.fn.apply(callbackItem.context);
  77. }
  78.  
  79. break;
  80. case 'interval:cleared':
  81. case 'timeout:cleared':
  82. delete workerTimer.callbacks[e.data.id];
  83. break;
  84. }
  85. },
  86.  
  87. // 往worker里面发送销毁指令
  88. clearInterval: (id) => worker.postMessage({ command: 'interval:clear', id: id }),
  89. clearTimeout: (id) => worker.postMessage({ command: 'timeout:clear', id: id }),
  90. };
  91. worker.onmessage = workerTimer.onMessage.bind(workerTimer);
  92.  
  93. let source = {
  94. version: 4,
  95. like: false,
  96. random: true,
  97. usePublic: false,
  98. data1: { available: true, values: ['弹幕①', '弹幕②'] },
  99. data2: { available: true, values: [] },
  100. data3: { available: true, values: [] },
  101. data4: { available: true, values: ['弹幕⑦'] },
  102. data5: { available: true, values: [] }
  103. },
  104. signInCheckbox, hideLoginGuideCheckbox, hideHarunaCheckbox, hideShopCheckbox, noSleepCheckbox, hideGiftControlCheckbox,
  105. hideRoomFeedCheckbox, hideRoomInfoCheckbox, hideNoticeCheckbox, hideFooterCheckbox, lotteryCheckbox, closeLotteryCheckbox,
  106. hesitationCheckbox, hidePrivacyCheckbox, hideRoomStatusCheckbox, setPublicCheckbox, hideBusinessCheckbox,
  107. hideRankListCheckbox, showLiveAreaCheckbox,
  108. group1Checkbox, group2Checkbox, group3Checkbox, group4Checkbox, group5Checkbox,
  109. rdCheckbox, usePublicCheckbox, autoLikeCheckbox,
  110. dmInput, divSetting, dataText1, dataText2, dataText3, dataText4, dataText5, signInput, hesitateInput,
  111. dmButtonSend, beforeSpan, afterSpan, spanApplyMsg, divUpdateInfo, btnStartText,
  112. baseInfo = {}, config = {}, waiters = [], data = [], ws = null, wsHostList = [], wsCmds = [],
  113. sendTimer = null, signInTimer = null, miniCloseTimer, noSleepTimer, noSleepTimeouter, btnLotteryTimer,
  114. divSendBtnTimer, autoLikeTimer, clickLikeBtnTimer, wsHeartBeatTimer, wsReconnectWsTimer,
  115. count = 0, waitCount = 200, arrayIndex = 0, default_timeout = 600, wsHostIndex = -1, wsConnectCount = 30,
  116. lotteryChecked = 'lottery_checked', closeLotteryChecked = 'close_lottery_checked', hesitationChecked = 'hesitation_checked',
  117. hesitationExpiry = 'hesitation_expiry', wsToken = '', wsAuth = '',
  118. gmNotice = obj => { alert(''); },
  119. getGmValue = (key, defaultValue) => { return null; },
  120. setGmValue = (key, obj) => { console.warn('===> No implementation "setGmValue" method.'); },
  121. delGmValue = key => { console.warn('===> No implementation "delGmValue" method.'); };
  122.  
  123. const version = '1.7.2', upodateInfo = 'WebSocket', noticeTimeout = 10e3,
  124. icoUrl = 'https://www.bilibili.com/favicon.ico',
  125. roomId = window.location.pathname.replace(/^\/(\S+\/)*/g, ''),
  126. textEncoder = new TextEncoder('utf-8'),
  127. textDecoder = new TextDecoder('utf-8'),
  128. eventTarget = new EventTarget(),
  129. eventTypeEnum = Object.freeze({authReply: 'AUTH_REPLY', heartBeatReply: 'HEARTBEAT_REPLY', danmuMsg: 'DANMU_MSG',
  130. reenterLiveRoom: 'REENTER_LIVE_ROOM', roomChange: 'ROOM_CHANGE', stopLiveRoomList: 'STOP_LIVE_ROOM_LIST',
  131. cutOff: 'CUT_OFF', anchorLotStart: 'ANCHOR_LOT_START', anchorLotEnd: 'ANCHOR_LOT_END', preparing: 'PREPARING',
  132. live: 'LIVE'}),
  133. onEvent = (eventTyppe, callback) => eventTarget.addEventListener(eventTyppe, e => callback(e.detail)),
  134. setGmGetValue = callback => getGmValue = callback,
  135. setGmSetValue = callback => setGmValue = callback,
  136. setGmDelValue = callback => delGmValue = callback,
  137. setGmNotice = callback => gmNotice = callback,
  138. setBaseInfo = obj => {
  139. baseInfo = obj;
  140. console.log(`===> 接收基础数据`);
  141. console.info(baseInfo);
  142. },
  143. arrayInfo = () => console.info(data),
  144. getRid = () => {return window.__STORE__?.baseInfoRoom.roomID || 0;},
  145. getRuid = () => {return window.__STORE__?.baseInfoAnchor?.uid || 0},
  146. getUid = () => {return window.__STORE__?.baseInfoUser?.uid || 0},
  147. isNull = str => {
  148. if (!str || str == "") {
  149. return true;
  150. }
  151.  
  152. let regu = "^[ ]+$";
  153. let re = new RegExp(regu);
  154. return re.test(str);
  155. },
  156. compareVersion = (ver1, ver2) => {
  157. if (isNull(ver1)) return -1;
  158. if (isNull(ver2)) return 1;
  159.  
  160. const arr1 = ver1.split('.').map(x => x * 1),
  161. arr2 = ver2.split('.').map(x => x * 1),
  162. len = Math.max(arr1.length, arr2.length);
  163. for (let i = 0; i < len; i++) {
  164. if ((arr1[i] || 0) > (arr2[i] || 0)) return 1;
  165. if ((arr1[i] || 0) < (arr2[i] || 0)) return -1;
  166. }
  167.  
  168. return 0;
  169. },
  170. getCookie = name => {
  171. let key = name + '=';
  172. const cookies = document.cookie.split(';');
  173. for(var i = 0; i < cookies.length; i++) {
  174. var cookie = cookies[i].trim();
  175. if (cookie.indexOf(key) == 0)
  176. return cookie.substring(key.length, cookie.length);
  177. }
  178. return '';
  179. },
  180. decompressBrotli = async arrayBuff => {
  181. const stream = new DecompressionStream('brotli');
  182. const decompressedStream = new Response(arrayBuff.stream().pipeThrough(stream));
  183. const result = await decompressedStream.arrayBuffer();
  184. return new Uint8Array(result);
  185. },
  186. initCss = () => {
  187. let linkElement = document.createElement('link');
  188. linkElement.rel = 'stylesheet';
  189. linkElement.href = 'https://unpkg.zhimg.com/element-ui/lib/theme-chalk/index.css';
  190. document.head.appendChild(linkElement);
  191.  
  192. // 图标库 https://ionic.io/ionicons
  193. // let scriptElement = document.createElement('script');
  194. // scriptElement.src = 'https://unpkg.com/ionicons@5.5.2/dist/ionicons.js';
  195. // document.head.appendChild(scriptElement);
  196.  
  197. let customerStyle = document.createElement('style');
  198. customerStyle.setAttribute('type', 'text/css');
  199. customerStyle.innerHTML = '.danmu-group-title{font-size:14px;padding-left:2px;color:rgb(18,56,141);display:inline;margin-right:60%;vertical-align:middle;}.danmu-group-textarea{width:98%;min-height:100px;height:16%;margin:1px 0px 4px;border:0px;resize:none;}.el-button{display:inline-block;line-height:1;white-space:nowrap;cursor:pointer;background:#FFF;border:1px solid #DCDFE6;color:#606266;-webkit-appearance:none;text-align:center;-webkit-box-sizing:border-box;box-sizing:border-box;outline:0;margin:0;-webkit-transition:.1s;transition:.1s;font-weight:500;padding:12px 20px;font-size:14px;border-radius:4px}.el-button.is-circle{border-radius:50%;padding:12px}.el-button--mini.is-circle{padding:3px;}.el-button:focus,.el-button:hover{color:#409EFF;border-color:#c6e2ff;background-color:#ecf5ff}.el-icon-close.is-circle{padding:5px;color:#ff0000;border:1px solid #ff0000;margin-left:20px;}.el-icon-check.is-circle{padding:5px;color:#0000ff;border:1px solid #0000ff;margin-left:20px;}input[type="checkbox"]{display:none;}.switch-check{display:inline-block;margin:0 5px;vertical-align:middle;}.switch-check-label{display:inline-block;vertical-align:middle;border:1px solid #bdc3c7;border-radius:60px;width:40px;height:18px;position:relative;transition:all .3s;cursor:pointer;}.switch-check-label:before{width:14px;height:14px;content:"";display:inline-block;background-color:#bdc3c7;border-radius:100%;position:absolute;top:2px;left:4px;transition:all .3s;}.switch-check :checked ~ label{background-color:#26b22b;border-color:#26b22b;}.switch-check :checked ~ label:before{left:22px;background-color:#fff;}.switch-check-group{margin-top:5px;width:95%;}.danmu-random-setting-panel{background-color:#e7f1fb;border-radius:10px;width:100%;height:100%;overflow-y:auto;position:absolute;left:0px;top:0px;z-index:999;display:none;}.danmu-random-setting-panel::-webkit-scrollbar{width:4px;height:4px;}.danmu-random-setting-panel::-webkit-scrollbar-thumb{border-radius:5px;-webkit-box-shadow:inset 0 0 5px rgba(0,0,0,0.2);background:rgba(0,0,0,0.2);}.danmu-random-setting-panel::-webkit-scrollbar-track{-webkit-box-shadow:inset 0 0 5px rgba(0,0,0,0.2);border-radius:0;background:rgba(0,0,0,0.1);}.danmu-random-setting-title{text-align:center;font-size:16px;font-weight:700;color:#1c5adc;line-height:30px;}.danmu-random-setting-title-sub{display:inline-block;color:#ee8b8b;height:24px;vertical-align:sub;-webkit-transform:scale(0.7);}.danmu-random-setting-tips{color:#0b81cc;text-align:center;font-style:italic;}.module-update-info{color:#0b81cc;text-indent:2em;font-size:13px;font-weight:700;margin:8px 0;padding:2px 0;background-color:#ffffff;}.update-info-text{color:#f00;vertical-align:-webkit-baseline-middle;}.danmu-random-setting-bottom{width:100%;line-height:35px;}.danmu-random-switch-button-title{font-size:14px;vertical-align:middle;margin-left:5px;color:#095ca2;cursor:help;}.danmu-random-setting-success-tips{text-align:center;display:inline-block;vertical-align:middle;width:40%;}.danmu-random-setting-success-text{font-size:16px;color:#128712;display:none;}.danmu-random-set-button-container{display:inline-block;vertical-align:middle;}.global-setting-tip{padding-left:10px;color:red;font-size:14px;font-weight:700;cursor:help;}.disabled{color:#ababab;cursor:not-allowed;}.clean-cache-btn{min-width:70px;font-size:14px;border-radius:4px;color:#fff;background:#d99d1b;border:0px;cursor:pointer;vertical-align:middle;line-height:30px;}.clean-cache-btn:hover{background:rgba(217,157,27,0.8);color:#000}.danmu-btn{min-width:65px;height:24px;font-size:12px;border-radius:4px;color:rgb(255,255,255);background:rgb(217,157,27);border:0px;cursor:pointer;line-height:1;display:inline-flex;justify-content:center;align-items:center;}.danmu-btn:hover{background:var(--color)!important;}.danmu-text-span{color:#095ca2;font-size:20px;vertical-align:middle;font-weight:700}.danmu-second-input{width:70px;height:20px;margin:0px 3px;border:0px;border-radius:3px;font-size:18px}.not-display{display:none !important;}';
  200. document.head.appendChild(customerStyle);
  201. },
  202. initScript = () => {
  203. let script = document.createElement('script');
  204. script.type = 'text/javascript';
  205. // script.src = 'https://cdn.jsdelivr.net/npm/crypto-js@4.1.1/crypto-js.js';
  206. script.src = 'https://cdnjs.cloudflare.com/ajax/libs/pako/2.1.0/pako_inflate.min.js';
  207. document.head.appendChild(script);
  208. },
  209. getCurrentTimestamp = () => new Date().getTime(),
  210. send = (msg, index) => {
  211. let dmTextArea = document.getElementById('chat-control-panel-vm').querySelector('textarea');
  212. if (!dmTextArea) {
  213. alert('找不到输入弹幕文本框,请尝试刷新页面');
  214. return;
  215. }
  216. if (!isNull(dmTextArea.value)) {
  217. console.log(`===> 有内容正在编辑,跳过该次发送任务`);
  218. return;
  219. }
  220.  
  221. let btnSend = document.getElementsByClassName('bl-button bl-button--primary')[0];
  222. if (!btnSend) {
  223. alert('找不到发送按钮,请尝试刷新页面');
  224. return;
  225. }
  226. dmTextArea.value = msg;
  227. dmTextArea.dispatchEvent(new Event('input', { "bubbles": true, "cancelable": true }));
  228. btnSend.click();
  229. // ++count;
  230. // console.log('===> ' + new Date().toLocaleString() + ' 弹幕发送成功 ' + count + ' 次,第【' + index + '】条数据 === ' + msg);
  231. },
  232. randomSort = arr => {
  233. for (let i = 0; i < arr.length; i++) {
  234. const rdIndex = Math.floor(Math.random() * arr.length);
  235. const temp = arr[i];
  236. arr[i] = arr[rdIndex];
  237. arr[rdIndex] = temp;
  238. }
  239.  
  240. return arr;
  241. },
  242. clearWaiters = () => {
  243. for (let i = 0; i < waiters.length; i++) {
  244. workerTimer.clearInterval(waiters[i]);
  245. waiters[i] = null;
  246. }
  247.  
  248. waiters = [];
  249. },
  250. signInFunc = () => {
  251. if (signInCheckbox.checked) {
  252. if (!signInTimer) {
  253. let defaultText = isNull(baseInfo.text) ? baseInfo.text : '打卡';
  254. let timestamp = new Date(new Date(new Date().setDate(new Date().getDate() + 1)).toDateString()).getTime() - getCurrentTimestamp();
  255. console.log('===> 设置凌晨打卡定时器【' + timestamp + '】');
  256. signInput.value = isNull(config.signInText) ? defaultText : config.signInText;
  257. signInTimer = workerTimer.setTimeout(() => {
  258. send(isNull(signInput.value) ? defaultText : signInput.value, 0);
  259. console.log('===> 设置下一次打卡');
  260. workerTimer.clearTimeout(signInTimer);
  261. signInTimer = null;
  262. signInFunc();
  263. }, timestamp);
  264. }
  265. } else if (signInTimer) {
  266. console.log('===> 关闭自动打卡功能');
  267. workerTimer.clearTimeout(signInTimer);
  268. signInTimer = null;
  269. }
  270. },
  271. setSource = obj => {
  272. dataText1.value = obj.data1.values.length ? obj.data1.values.join('|') : [];
  273. dataText2.value = obj.data2.values.length ? obj.data2.values.join('|') : [];
  274. dataText3.value = obj.data3.values.length ? obj.data3.values.join('|') : [];
  275. dataText4.value = obj.data4.values.length ? obj.data4.values.join('|') : [];
  276. dataText5.value = obj.data5.values.length ? obj.data5.values.join('|') : [];
  277. },
  278. runCheckbox = () => {
  279. usePublicFunc();
  280. hideFooterFunc();
  281. hideGiftControlFunc();
  282. hideLoginGuideFunc();
  283. hideHarunaFunc();
  284. hideShopFunc();
  285. hidePrivacyFunc();
  286. hideRoomStatusFunc();
  287. hideBusinessFunc();
  288. hideRankListFunc();
  289. noSleepFunc();
  290. signInFunc();
  291. lotteryFunc();
  292. hesitationFunc();
  293. closeLotteryFunc();
  294. autoLikeFunc();
  295. // autoPlay();
  296. hideRoomFeedFunc();
  297. hideRoomInfoFunc();
  298. hideNoticeFunc();
  299. showLiveAreaFunc();
  300. let hideTimeout = workerTimer.setTimeout(() => {
  301. workerTimer.clearTimeout(hideTimeout);
  302. hideRoomFeedFunc();
  303. hideRoomInfoFunc();
  304. hideNoticeFunc();
  305. showLiveAreaFunc();
  306. }, 1e3);
  307. },
  308. setOperationSetting = () => {
  309. setPublicCheckbox.checked = false;
  310. rdCheckbox.checked = source.random;
  311. autoLikeCheckbox.checked = source.like;
  312. usePublicCheckbox.checked = source.usePublic;
  313. dmInput.value = source.interval || default_timeout;
  314. group1Checkbox.checked = source.data1.available;
  315. group2Checkbox.checked = source.data2.available;
  316. group3Checkbox.checked = source.data3.available;
  317. group4Checkbox.checked = source.data4.available;
  318. group5Checkbox.checked = source.data5.available;
  319.  
  320. signInCheckbox.checked = config.autoSignIn;
  321. noSleepCheckbox.checked = config.noSleep;
  322. hideLoginGuideCheckbox.checked = config.hideLoginGuide;
  323. hideHarunaCheckbox.checked = config.hideHaruna;
  324. hideShopCheckbox.checked = config.hideShop;
  325. hideGiftControlCheckbox.checked = config.hideGift;
  326. hideRoomFeedCheckbox.checked = config.hideRoomFeed;
  327. hideRoomInfoCheckbox.checked = config.hideRoomInfo;
  328. hideNoticeCheckbox.checked = config.hideNotice;
  329. hideFooterCheckbox.checked = config.hideFooter;
  330. lotteryCheckbox.checked = config.lottery;
  331. hesitationCheckbox.checked = config.hesitation;
  332. closeLotteryCheckbox.checked = config.closeLottery;
  333. hidePrivacyCheckbox.checked = config.noPrivacy;
  334. hideRoomStatusCheckbox.checked = config.hideWatermark;
  335. hideBusinessCheckbox.checked = config.hideBusiness;
  336. hideRankListCheckbox.checked = config.hideRankList;
  337. showLiveAreaCheckbox.checked = config.showLiveArea;
  338. runCheckbox();
  339. },
  340. openSetting = () => divSetting.style.display = 'block',
  341. closeSetting = () => {
  342. setOperationSetting();
  343. divSetting.style.display = 'none';
  344. },
  345. initData = () => {
  346. if (source.data1.values.length <= 0
  347. && source.data2.values.length <= 0
  348. && source.data3.values.length <= 0
  349. && source.data4.values.length <= 0
  350. && source.data5.values.length <= 0) {
  351. return data ? data : [];
  352. }
  353.  
  354. let result = [];
  355. result = source.data1.available ? result.concat(source.data1.values) : result;
  356. result = source.data2.available ? result.concat(source.data2.values) : result;
  357. result = source.data3.available ? result.concat(source.data3.values) : result;
  358. result = source.data4.available ? result.concat(source.data4.values) : result;
  359. result = source.data5.available ? result.concat(source.data5.values) : result;
  360. data = result;
  361. rdCheckbox.checked ? data = randomSort(result) : arrayIndex = 0;
  362. },
  363. flashMsg = (txt, back, color) => {
  364. spanApplyMsg.textContent = txt;
  365. spanApplyMsg.style.display = 'block';
  366. if (color) {
  367. spanApplyMsg.style.color = color;
  368. }
  369. else {
  370. spanApplyMsg.style.color = '#128712';
  371. }
  372.  
  373. let hideTipTimer = workerTimer.setTimeout(() => {
  374. workerTimer.clearTimeout(hideTipTimer);
  375. spanApplyMsg.style.display = 'none';
  376. spanApplyMsg.textContent = '';
  377. if (back) {
  378. divSetting.style.display = 'none';
  379. }
  380. }, 1.5e3);
  381. },
  382. save = () => {
  383. if (!baseInfo || isNull(baseInfo.default) || isNull(baseInfo.config)) {
  384. flashMsg('保存失败', false, 'red');
  385. return;
  386. }
  387. if (baseInfo.config) {
  388. config.autoSignIn = signInCheckbox.checked;
  389. config.signInText = signInput.value;
  390. config.noSleep = noSleepCheckbox.checked;
  391. config.hideLoginGuide = hideLoginGuideCheckbox.checked;
  392. config.hideHaruna = hideHarunaCheckbox.checked;
  393. config.hideShop = hideShopCheckbox.checked;
  394. config.hideGift = hideGiftControlCheckbox.checked;
  395. config.hideRoomFeed = hideRoomFeedCheckbox.checked;
  396. config.hideRoomInfo = hideRoomInfoCheckbox.checked;
  397. config.hideNotice = hideNoticeCheckbox.checked;
  398. config.hideFooter = hideFooterCheckbox.checked;
  399. config.lottery = lotteryCheckbox.checked;
  400. window.localStorage.setItem(lotteryChecked, lotteryCheckbox.checked);
  401. config.hesitation = hesitationCheckbox.checked;
  402. window.localStorage.setItem(hesitationChecked, hesitationCheckbox.checked);
  403. config.hesitationExpiry = hesitateInput.value;
  404. window.localStorage.setItem(hesitationExpiry, hesitateInput.value);
  405. config.closeLottery = closeLotteryCheckbox.checked;
  406. window.localStorage.setItem(closeLotteryChecked, config.closeLottery);
  407. config.noPrivacy = hidePrivacyCheckbox.checked;
  408. config.hideWatermark = hideRoomStatusCheckbox.checked;
  409. config.hideBusiness = hideBusinessCheckbox.checked;
  410. config.hideRankList = hideRankListCheckbox.checked;
  411. config.showLiveArea = showLiveAreaCheckbox.checked;
  412. setGmValue(baseInfo.config, config);
  413. }
  414.  
  415. let v1 = isNull(dataText1.value) ? [] : dataText1.value.split('|'),
  416. v2 = isNull(dataText2.value) ? [] : dataText2.value.split('|'),
  417. v3 = isNull(dataText3.value) ? [] : dataText3.value.split('|'),
  418. v4 = isNull(dataText4.value) ? [] : dataText4.value.split('|'),
  419. v5 = isNull(dataText5.value) ? [] : dataText5.value.split('|');
  420. source.interval = dmInput.value;
  421. source.random = rdCheckbox.checked;
  422. source.like = autoLikeCheckbox.checked;
  423. source.usePublic = usePublicCheckbox.checked;
  424. source.data1.available = group1Checkbox.checked;
  425. source.data2.available = group2Checkbox.checked;
  426. source.data3.available = group3Checkbox.checked;
  427. source.data4.available = group4Checkbox.checked;
  428. source.data5.available = group5Checkbox.checked;
  429. if (!usePublicCheckbox.checked) {
  430. source.data1.values = v1;
  431. source.data2.values = v2;
  432. source.data3.values = v3;
  433. source.data4.values = v4;
  434. source.data5.values = v5;
  435. }
  436. setGmValue(roomId, source);
  437. if (setPublicCheckbox.checked) {
  438. let ps = {data1:{},data2:{},data3:{},data4:{},data5:{}};
  439. ps.data1.values = v1;
  440. ps.data2.values = v2;
  441. ps.data3.values = v3;
  442. ps.data4.values = v4;
  443. ps.data5.values = v5;
  444. setGmValue(baseInfo.default, ps);
  445. }
  446. if (usePublicCheckbox.checked) {
  447. source.data1.values = v1;
  448. source.data2.values = v2;
  449. source.data3.values = v3;
  450. source.data4.values = v4;
  451. source.data5.values = v5;
  452. }
  453. initData();
  454. flashMsg('设置成功', true);
  455. },
  456. cleanCache = () => {
  457. if (baseInfo.config && config) {
  458. config.script = '';
  459. config.moduleVersion = '0.0.0';
  460. config.lastUpdate = '清除脚本缓存';
  461. setGmValue(baseInfo.config, config);
  462. flashMsg('清除成功');
  463. } else {
  464. console.warn('元数据丢失');
  465. flashMsg('操作失败', false, 'red');
  466. }
  467. },
  468. danmu = () => {
  469. if (data.length < 1) {
  470. // gmNotice({
  471. // text: '请任意在一个分组里输入一条弹幕',
  472. // title: '没有弹幕数据,请先设置',
  473. // image: icoUrl,
  474. // highlight: true,
  475. // timeout: noticeTimeout
  476. // });
  477. alert('请先设置弹幕');
  478. return false;
  479. }
  480. if (rdCheckbox.checked) {
  481. arrayIndex = Math.floor((Math.random() * data.length));
  482. }
  483.  
  484. send(data[arrayIndex], arrayIndex);
  485. ++arrayIndex;
  486. if (arrayIndex >= data.length) {
  487. arrayIndex = 0;
  488. }
  489.  
  490. return true;
  491. },
  492. offOrOn = () => {
  493. let timeout = 0;
  494. if (sendTimer) {
  495. workerTimer.clearInterval(sendTimer);
  496. sendTimer = null;
  497. dmButtonSend.style.removeProperty('background');
  498. dmButtonSend.style.removeProperty('--color');
  499. dmInput.removeAttribute("disabled");
  500. btnStartText.textContent = '开始';
  501. } else {
  502. timeout = (dmInput.value || default_timeout) * 1e3;
  503. if (!danmu()) {
  504. return;
  505. }
  506.  
  507. sendTimer = workerTimer.setInterval(danmu, timeout);
  508. dmButtonSend.style.background = 'rgba(255,0,0,1)';
  509. dmButtonSend.style.setProperty('--color', 'rgba(255,0,0,0.8)');
  510. dmInput.setAttribute('disabled', 'disabled');
  511. btnStartText.textContent = '停止';
  512. }
  513. },
  514. createSwitch = (id, txt, title, func, container, indent, width, hidden, rear, disabled) => {
  515. let checkbox = document.createElement('input');
  516. checkbox.type = 'checkbox';
  517. checkbox.id = id;
  518. checkbox.checked = false;
  519. if (func && !disabled) {
  520. checkbox.addEventListener('click', func);
  521. }
  522.  
  523. let lblCheckbox = document.createElement('label');
  524. lblCheckbox.setAttribute('for', id);
  525. lblCheckbox.classList.add('switch-check-label');
  526.  
  527. let descSpan = document.createElement('span');
  528. descSpan.textContent = txt;
  529. descSpan.title = title;
  530. descSpan.classList.add('danmu-random-switch-button-title');
  531. if (disabled) {
  532. checkbox.disabled = true;
  533. checkbox.classList.add('disabled');
  534. lblCheckbox.classList.add('disabled');
  535. descSpan.classList.add('disabled');
  536. }
  537.  
  538. let divCheckbox = document.createElement('div');
  539. divCheckbox.id = id + 'Div';
  540. divCheckbox.classList.add('switch-check');
  541. divCheckbox.classList.add('switch-check-group');
  542. divCheckbox.appendChild(checkbox);
  543. divCheckbox.appendChild(lblCheckbox);
  544. divCheckbox.appendChild(descSpan);
  545. if (!isNull(indent)) {
  546. divCheckbox.style.marginLeft = indent;
  547. }
  548. if (!isNull(width)) {
  549. divCheckbox.style.width = width;
  550. }
  551. if (hidden) {
  552. divCheckbox.style.setProperty('display', 'none');
  553. }
  554. if (rear) {
  555. divCheckbox.appendChild(rear);
  556. }
  557.  
  558. container.appendChild(divCheckbox);
  559. return checkbox;
  560. },
  561. buildPanel = () => {
  562. /* ----------------------------------------- head ----------------------------------------- */
  563. let divSettingTitle = document.createElement('div');
  564. divSettingTitle.textContent = '弹幕设置';
  565. divSettingTitle.classList.add('danmu-random-setting-title');
  566.  
  567. let divSub = document.createElement('div');
  568. divSub.textContent = version;
  569. divSub.classList.add('danmu-random-setting-title-sub');
  570. divSettingTitle.appendChild(divSub);
  571.  
  572. let divTip = document.createElement('div');
  573. divTip.classList.add('danmu-random-setting-tips');
  574. divTip.innerHTML = '任一分组内输入弹幕即可,多条用<span style="color:#dc6b07;margin:0 2px 0 4px;font-weight:700;font-style:normal;">竖线</span>分隔';
  575.  
  576. divUpdateInfo = document.createElement('div');
  577. divUpdateInfo.classList.add('module-update-info');
  578. divUpdateInfo.innerHTML = `<span class="update-info-text">消息提示:</span><span class="update-info-text" style="color:#0f6ba6;">${baseInfo.msg || upodateInfo}</span>`;
  579. /* ----------------------------------------- head ----------------------------------------- */
  580.  
  581. /* ----------------------------------------- textarea 1 ----------------------------------------- */
  582. let divText1 = document.createElement('div');
  583. divText1.textContent = '分组 1 :';
  584. divText1.classList.add('danmu-group-title');
  585.  
  586. group1Checkbox = document.createElement('input');
  587. group1Checkbox.type = 'checkbox';
  588. group1Checkbox.id = 'group1Checkbox';
  589. group1Checkbox.checked = true;
  590.  
  591. let lblGroup1Checkbox = document.createElement('label');
  592. lblGroup1Checkbox.setAttribute('for', 'group1Checkbox');
  593. lblGroup1Checkbox.classList.add('switch-check-label');
  594.  
  595. let divGroup1Checkbox = document.createElement('div');
  596. divGroup1Checkbox.classList.add('switch-check');
  597. divGroup1Checkbox.appendChild(group1Checkbox);
  598. divGroup1Checkbox.appendChild(lblGroup1Checkbox);
  599.  
  600. dataText1 = document.createElement('textarea');
  601. dataText1.classList.add('danmu-group-textarea');
  602. dataText1.setAttribute('placeholder', '请输入弹幕,多条弹幕请用“|”分隔');
  603. /* ----------------------------------------- textarea 1 ----------------------------------------- */
  604.  
  605. /* ----------------------------------------- textarea 2 ----------------------------------------- */
  606. let divText2 = document.createElement('div');
  607. divText2.textContent = '分组 2 :';
  608. divText2.classList.add('danmu-group-title');
  609.  
  610. group2Checkbox = document.createElement('input');
  611. group2Checkbox.type = 'checkbox';
  612. group2Checkbox.id = 'group2Checkbox';
  613. group2Checkbox.checked = true;
  614.  
  615. let lblGroup2Checkbox = document.createElement('label');
  616. lblGroup2Checkbox.setAttribute('for', 'group2Checkbox');
  617. lblGroup2Checkbox.classList.add('switch-check-label');
  618.  
  619. let divGroup2Checkbox = document.createElement('div');
  620. divGroup2Checkbox.classList.add('switch-check');
  621. divGroup2Checkbox.appendChild(group2Checkbox);
  622. divGroup2Checkbox.appendChild(lblGroup2Checkbox);
  623.  
  624. dataText2 = document.createElement('textarea');
  625. dataText2.classList.add('danmu-group-textarea');
  626. dataText2.setAttribute('placeholder', '请输入弹幕,多条弹幕请用“|”分隔');
  627. /* ----------------------------------------- textarea 2 ----------------------------------------- */
  628.  
  629. /* ----------------------------------------- textarea 3 ----------------------------------------- */
  630. let divText3 = document.createElement('div');
  631. divText3.textContent = '分组 3 :';
  632. divText3.classList.add('danmu-group-title');
  633.  
  634. group3Checkbox = document.createElement('input');
  635. group3Checkbox.type = 'checkbox';
  636. group3Checkbox.id = 'group3Checkbox';
  637. group3Checkbox.checked = true;
  638.  
  639. let lblGroup3Checkbox = document.createElement('label');
  640. lblGroup3Checkbox.setAttribute('for', 'group3Checkbox');
  641. lblGroup3Checkbox.classList.add('switch-check-label');
  642.  
  643. let divGroup3Checkbox = document.createElement('div');
  644. divGroup3Checkbox.classList.add('switch-check');
  645. divGroup3Checkbox.appendChild(group3Checkbox);
  646. divGroup3Checkbox.appendChild(lblGroup3Checkbox);
  647.  
  648. dataText3 = document.createElement('textarea');
  649. dataText3.classList.add('danmu-group-textarea');
  650. dataText3.setAttribute('placeholder', '请输入弹幕,多条弹幕请用“|”分隔');
  651. /* ----------------------------------------- textarea 3 ----------------------------------------- */
  652.  
  653. /* ----------------------------------------- textarea 4 ----------------------------------------- */
  654. let divText4 = document.createElement('div');
  655. divText4.textContent = '分组 4 :';
  656. divText4.classList.add('danmu-group-title');
  657.  
  658. group4Checkbox = document.createElement('input');
  659. group4Checkbox.type = 'checkbox';
  660. group4Checkbox.id = 'group4Checkbox';
  661. group4Checkbox.checked = true;
  662.  
  663. let lblGroup4Checkbox = document.createElement('label');
  664. lblGroup4Checkbox.setAttribute('for', 'group4Checkbox');
  665. lblGroup4Checkbox.classList.add('switch-check-label');
  666.  
  667. let divGroup4Checkbox = document.createElement('div');
  668. divGroup4Checkbox.classList.add('switch-check');
  669. divGroup4Checkbox.appendChild(group4Checkbox);
  670. divGroup4Checkbox.appendChild(lblGroup4Checkbox);
  671.  
  672. dataText4 = document.createElement('textarea');
  673. dataText4.classList.add('danmu-group-textarea');
  674. dataText4.setAttribute('placeholder', '请输入弹幕,多条弹幕请用“|”分隔');
  675. /* ----------------------------------------- textarea 4 ----------------------------------------- */
  676.  
  677. /* ----------------------------------------- textarea 5 ----------------------------------------- */
  678. let divText5 = document.createElement('div');
  679. divText5.textContent = '分组 5 :';
  680. divText5.classList.add('danmu-group-title');
  681.  
  682. group5Checkbox = document.createElement('input');
  683. group5Checkbox.type = 'checkbox';
  684. group5Checkbox.id = 'group5Checkbox';
  685. group5Checkbox.checked = true;
  686.  
  687. let lblGroup5Checkbox = document.createElement('label');
  688. lblGroup5Checkbox.setAttribute('for', 'group5Checkbox');
  689. lblGroup5Checkbox.classList.add('switch-check-label');
  690.  
  691. let divGroup5Checkbox = document.createElement('div');
  692. divGroup5Checkbox.classList.add('switch-check');
  693. divGroup5Checkbox.appendChild(group5Checkbox);
  694. divGroup5Checkbox.appendChild(lblGroup5Checkbox);
  695.  
  696. dataText5 = document.createElement('textarea');
  697. dataText5.classList.add('danmu-group-textarea');
  698. dataText5.setAttribute('placeholder', '请输入弹幕,多条弹幕请用“|”分隔');
  699. /* ----------------------------------------- textarea 5 ----------------------------------------- */
  700.  
  701.  
  702. /* ----------------------------------------- send interval ----------------------------------------- */
  703. beforeSpan = document.createElement('span');
  704. beforeSpan.textContent = '设置弹幕每';
  705. beforeSpan.classList.add('danmu-text-span');
  706. beforeSpan.style.marginLeft = '4px';
  707.  
  708. dmInput = document.createElement('input');
  709. dmInput.value = default_timeout;
  710. dmInput.classList.add('danmu-second-input');
  711. dmInput.setAttribute('oninput', "this.value = this.value.replace(/[^0-9]/g, '')");
  712.  
  713. afterSpan = document.createElement('span');
  714. afterSpan.textContent = '秒发送一次';
  715. afterSpan.classList.add('danmu-text-span');
  716. afterSpan.style.marginRight = '4px';
  717.  
  718. let divSendInterval = document.createElement('div');
  719. divSendInterval.appendChild(beforeSpan);
  720. divSendInterval.appendChild(dmInput);
  721. divSendInterval.appendChild(afterSpan);
  722. /* ----------------------------------------- send interval ----------------------------------------- */
  723.  
  724.  
  725. /* ----------------------------------------- different room setting ----------------------------------------- */
  726. let divRoomSetting = document.createElement('div');
  727. divRoomSetting.appendChild(divText1);
  728. divRoomSetting.appendChild(divGroup1Checkbox);
  729. divRoomSetting.appendChild(dataText1);
  730. divRoomSetting.appendChild(divText2);
  731. divRoomSetting.appendChild(divGroup2Checkbox);
  732. divRoomSetting.appendChild(dataText2);
  733. divRoomSetting.appendChild(divText3);
  734. divRoomSetting.appendChild(divGroup3Checkbox);
  735. divRoomSetting.appendChild(dataText3);
  736. divRoomSetting.appendChild(divText4);
  737. divRoomSetting.appendChild(divGroup4Checkbox);
  738. divRoomSetting.appendChild(dataText4);
  739. divRoomSetting.appendChild(divText5);
  740. divRoomSetting.appendChild(divGroup5Checkbox);
  741. divRoomSetting.appendChild(dataText5);
  742. divRoomSetting.appendChild(divSendInterval);
  743. rdCheckbox = createSwitch('rdCheckbox', '随机从上面的弹幕中选出一条发送', '将合并所有分组数据,从中随机选出一条发送', null, divRoomSetting);
  744. usePublicCheckbox = createSwitch('usePublicCheckbox', '使用共用弹幕源', '使用设置为共用弹幕作为弹幕源', usePublicFunc, divRoomSetting);
  745. autoLikeCheckbox = createSwitch('autoLikeCheckbox', '自动点赞该直播间', '每15秒内随机一个时间点点赞一次直播间(点赞1000次大概需要4小时)', autoLikeFunc, divRoomSetting, null, null, null, null);
  746.  
  747. let operationDescription = document.createElement('div');
  748. operationDescription.textContent = '以上设置对应各个直播间独立保存,无需刷新';
  749. operationDescription.title = '请点击设置面板底下的“✓”进行保存';
  750. operationDescription.classList.add('global-setting-tip');
  751. operationDescription.classList.add('switch-check-group');
  752. divRoomSetting.appendChild(operationDescription);
  753. /* ----------------------------------------- different room setting ----------------------------------------- */
  754.  
  755. /* ----------------------------------------- global setting ----------------------------------------- */
  756. let divGlobalSetting = document.createElement('div');
  757. divGlobalSetting.style.margin = '20px 0 10px';
  758.  
  759. operationDescription = document.createElement('div');
  760. operationDescription.textContent = '以下设置,需刷新其它直播间才能适用';
  761. operationDescription.title = '请点击设置面板底下的“✓”进行保存';
  762. operationDescription.classList.add('global-setting-tip');
  763. operationDescription.classList.add('switch-check-group');
  764. divGlobalSetting.appendChild(operationDescription);
  765.  
  766. signInput = document.createElement('input');
  767. signInput.id = 'signInputText';
  768. signInput.style.border = '0';
  769. signInput.style.width = '90px';
  770. signInput.setAttribute('placeholder', '输入打卡的文字');
  771.  
  772. hesitateInput = document.createElement('input');
  773. hesitateInput.style.border = '0';
  774. hesitateInput.style.width = '55px';
  775. hesitateInput.setAttribute('placeholder', '单位:秒');
  776. hesitateInput.setAttribute('oninput', "this.value = this.value.replace(/[^0-9]/g, '')");
  777.  
  778. setPublicCheckbox = createSwitch('setPublicCheckbox', '设为共用弹幕源', '把这个直播间的弹幕共享给其它直播间使用,先后设置时,后面的会覆盖前面的设置', setPublicFunc, divGlobalSetting);
  779. signInCheckbox = createSwitch('signInCheckbox', '打卡弹幕(需登录):', '每日零点发送一条打卡弹幕', signInFunc, divGlobalSetting, null, null, false, signInput);
  780. lotteryCheckbox = createSwitch('lotteryCheckbox', '自动参与天选时刻抽奖(需登录)', '自动点击参与按钮,请确保已经登录了阿B账号', lotteryFunc, divGlobalSetting);
  781. hesitationCheckbox = createSwitch('hesitationCheckbox', '随机犹豫期:', '(尝试应对人机校验,不一定有效,随机的范围:(0, 填的数字])不立刻参与天选时刻,这期间可以手动处理,免得自动参加后后悔(时间单位:秒)', hesitationFunc, divGlobalSetting, '23px', '90%', true, hesitateInput);
  782. closeLotteryCheckbox = createSwitch('closeLotteryCheckbox', '关闭天选时刻', '关闭天选时刻弹窗', closeLotteryFunc, divGlobalSetting);
  783. hideGiftControlCheckbox = createSwitch('hideGiftControlCheckbox', '隐藏礼物栏', '隐藏播放器底部的礼物栏', hideGiftControlFunc, divGlobalSetting);
  784. noSleepCheckbox = createSwitch('noSleepCheckbox', '防止直播间休眠', '防止直播间页面一段时间没操作之后进入休眠', noSleepFunc, divGlobalSetting, null, null, false);
  785. hideLoginGuideCheckbox = createSwitch('hideLoginGuideCheckbox', '隐藏播放器底部登录提示', '隐藏未登录时播放器底部显示的登录提示', hideLoginGuideFunc, divGlobalSetting);
  786. hideHarunaCheckbox = createSwitch('hideHarunaCheckbox', '隐藏看板娘立绘', '隐藏直播间Haruna立绘', hideHarunaFunc, divGlobalSetting);
  787. hideShopCheckbox = createSwitch('hideShopCheckbox', '隐藏购物提示', '隐藏播放器左上角的商店购物提示', hideShopFunc, divGlobalSetting);
  788. hideRoomFeedCheckbox = createSwitch('hideRoomFeedCheckbox', '隐藏主播动态', '隐藏播放器底下主播的动态栏', hideRoomFeedFunc, divGlobalSetting);
  789. hideRoomInfoCheckbox = createSwitch('hideRoomInfoCheckbox', '隐藏简介、荣誉,或直播间推荐列表', '隐藏播放器底下直播间推荐列表,不登录账号显示为主播的荣耀和简介', hideRoomInfoFunc, divGlobalSetting);
  790. hideNoticeCheckbox = createSwitch('hideNoticeCheckbox', '隐藏主播公告', '隐藏弹幕列表底下主播的公告', hideNoticeFunc, divGlobalSetting);
  791. hideFooterCheckbox = createSwitch('hideFooterCheckbox', '隐藏直播间页脚', '隐藏直播间底部的网页页脚', hideFooterFunc, divGlobalSetting);
  792. hidePrivacyCheckbox = createSwitch('hidePrivacyCheckbox', '隐藏隐私提示对话框', '隐藏隐私提示登录的对话框,被打码的昵称不保证变回正常', hidePrivacyFunc, divGlobalSetting);
  793. hideRoomStatusCheckbox = createSwitch('hideRoomStatusCheckbox', '隐藏直播水印', '隐藏播放器左上角的直播水印', hideRoomStatusFunc, divGlobalSetting);
  794. hideBusinessCheckbox = createSwitch('hideBusinessCheckbox', '隐藏商业性互动', '隐藏全站广播、PK、连MIC、连视频等', hideBusinessFunc, divGlobalSetting);
  795. hideRankListCheckbox = createSwitch('hideRankListCheckbox', '隐藏滚动排行榜', '隐藏顶部的人气榜、航海榜、礼物星球等', hideRankListFunc, divGlobalSetting);
  796. showLiveAreaCheckbox = createSwitch('showLiveArea', '显示直播分区', '显示直播间所属的直播分区', showLiveAreaFunc, divGlobalSetting);
  797. /* ----------------------------------------- global setting ----------------------------------------- */
  798.  
  799. /* ----------------------------------------- operation msg ----------------------------------------- */
  800. spanApplyMsg = document.createElement('span');
  801. spanApplyMsg.classList.add('danmu-random-setting-success-text');
  802.  
  803. let divApplyMsg = document.createElement('div');
  804. divApplyMsg.classList.add('danmu-random-setting-success-tips');
  805. divApplyMsg.appendChild(spanApplyMsg);
  806. /* ----------------------------------------- operation msg ----------------------------------------- */
  807. /* ----------------------------------------- clean cache ----------------------------------------- */
  808. let cleanCacheBtn = document.createElement('button');
  809. cleanCacheBtn.style.setProperty('display', 'none');
  810. cleanCacheBtn.textContent = '清除缓存';
  811. cleanCacheBtn.classList.add('clean-cache-btn');
  812. cleanCacheBtn.addEventListener('click', cleanCache);
  813. /* ----------------------------------------- clean cache ----------------------------------------- */
  814.  
  815. /* ----------------------------------------- save and close button ----------------------------------------- */
  816. let btnSave = document.createElement('i');
  817. btnSave.setAttribute('title', '保存');
  818. btnSave.style.padding = '5px';
  819. btnSave.classList.add('el-button');
  820. btnSave.classList.add('el-icon-check');
  821. btnSave.classList.add('is-circle');
  822. btnSave.addEventListener('click', save);
  823.  
  824. let btnClose = document.createElement('i');
  825. btnClose.setAttribute('title', '关闭');
  826. btnClose.style.padding = '5px';
  827. btnClose.classList.add('el-button');
  828. btnClose.classList.add('el-icon-close');
  829. btnClose.classList.add('is-circle');
  830. btnClose.addEventListener('click', closeSetting);
  831.  
  832. let divBtnSetting = document.createElement('div');
  833. divBtnSetting.classList.add('danmu-random-set-button-container');
  834. divBtnSetting.appendChild(cleanCacheBtn);
  835. divBtnSetting.appendChild(btnSave);
  836. divBtnSetting.appendChild(btnClose);
  837. /* ----------------------------------------- save and close button ----------------------------------------- */
  838.  
  839. /* ----------------------------------------- container ----------------------------------------- */
  840. let divBottomContainer = document.createElement('div');
  841. divBottomContainer.classList.add('danmu-random-setting-bottom');
  842. divBottomContainer.appendChild(divApplyMsg);
  843. divBottomContainer.appendChild(divBtnSetting);
  844.  
  845. let divOtherContainer = document.createElement('div');
  846. divOtherContainer.id = 'otherContainer';
  847.  
  848. let divContainer = document.createElement('div');
  849. divContainer.style.height = 'calc(98% - 30px - 25px)';
  850. divContainer.appendChild(divRoomSetting);
  851. divContainer.appendChild(divGlobalSetting);
  852. divContainer.appendChild(divOtherContainer);
  853. divContainer.appendChild(divBottomContainer);
  854. /* ----------------------------------------- container ----------------------------------------- */
  855.  
  856. divSetting = document.createElement('div');
  857. divSetting.id = 'danmu-setting-panel';
  858. divSetting.classList.add('danmu-random-setting-panel');
  859. divSetting.appendChild(divSettingTitle);
  860. divSetting.appendChild(divUpdateInfo);
  861. divSetting.appendChild(divTip);
  862. divSetting.appendChild(divContainer);
  863.  
  864. let asideAreaVm = document.getElementById('aside-area-vm');
  865. asideAreaVm.appendChild(divSetting);
  866.  
  867. },
  868. btnStart = btn => {
  869. const title = '开始定时发送';
  870. btnStartText = document.createElement('span');
  871. btnStartText.textContent = '开始';
  872. btnStartText.title = title;
  873. btnStartText.classList.add('txt');
  874.  
  875. dmButtonSend = document.createElement('button');
  876. dmButtonSend.title = title;
  877. //dmButtonSend.onclick = function() { alert('Hello world');}
  878. dmButtonSend.addEventListener('click', offOrOn);
  879. dmButtonSend.appendChild(btnStartText);
  880. if (btn) {
  881. copyAttributes(btn, dmButtonSend);
  882. const span = btn.querySelector('span');
  883. if (span) {
  884. copyAttributes(span, btnStartText);
  885. }
  886. }
  887. else {
  888. dmButtonSend.classList.add('danmu-btn');
  889. dmButtonSend.style.setProperty('--color', 'rgba(217,157,27,0.8)');
  890. }
  891. },
  892. btnSetting = () => {
  893. const title = '定时设置', divEmo = document.getElementsByClassName('emoticons-panel border-box')[0];
  894. let iElement = document.createElement('i');
  895. iElement.classList.add('el-icon-setting');
  896.  
  897. let btn = document.createElement('button');
  898. btn.title = title;
  899. btn.classList.add('el-button');
  900. btn.classList.add('el-button--mini');
  901. btn.classList.add('is-circle');
  902. btn.addEventListener('click', openSetting);
  903. btn.appendChild(iElement);
  904. if (divEmo) {
  905. let div = document.createElement('div');
  906. copyAttributes(divEmo, div);
  907. div.title = title;
  908. div.style.backgroundImage = 'none';
  909. div.style.position = 'absolute';
  910. div.style.right = '60px';
  911. div.style.bottom = '2px';
  912. div.appendChild(btn);
  913.  
  914. divEmo.style.position = 'absolute';
  915. divEmo.style.right = '60px';
  916. divEmo.style.top = '4px';
  917. return div;
  918. }
  919. else {
  920. btn.style.margin = '0 5px';
  921. return btn;
  922. }
  923. },
  924. copyAttributes = (oldNode, newNode) => {
  925. Array.prototype.forEach.call(oldNode.attributes, (item, index) => newNode.setAttribute(item.name, item.value));
  926. },
  927. setDisplay = (dom, property, important) => {
  928. if (important) {
  929. dom.style.setProperty('display', property, 'important');
  930. }
  931. else {
  932. dom.style.setProperty('display', property);
  933. }
  934. },
  935. blockDisplay = (dom, shwon) => {
  936. if (shwon) {
  937. setDisplay(dom, 'block', true);
  938. }
  939. else {
  940. dom.style.removeProperty('display');
  941. }
  942. },
  943. noneDisplay = (dom, hidden) => {
  944. if (hidden) {
  945. setDisplay(dom, 'none', true);
  946. }
  947. else {
  948. dom.style.removeProperty('display');
  949. }
  950. },
  951. removeAttributeFromChildren = (dom, attr) => {
  952. dom.removeAttribute(attr);
  953. if (0 < dom.children.length) {
  954. for (let i = 0; i < dom.children.length; i++) {
  955. removeAttributeFromChildren(dom.children[i], attr);
  956. }
  957. }
  958. },
  959. setAttributeToChildren = (dom, attr, val) => {
  960. dom.setAttribute(attr, val);
  961. if (0 < dom.children.length) {
  962. for (let i = 0; i < dom.children.length; i++) {
  963. setAttributeToChildren(dom.children[i], attr, val);
  964. }
  965. }
  966. },
  967. hideLoginGuideFunc = () => {
  968. let dom = document.getElementById('switch-login-guide-vm');
  969. if (dom) {
  970. noneDisplay(dom, hideLoginGuideCheckbox.checked);
  971. }
  972. },
  973. hideHarunaFunc = () => {
  974. let dom = document.getElementById('my-dear-haruna-vm');
  975. if (dom) {
  976. noneDisplay(dom, hideHarunaCheckbox.checked);
  977. }
  978. },
  979. hideShopFunc = () => {
  980. let dom = document.getElementById('shop-popover-vm');
  981. if (dom) {
  982. noneDisplay(dom, hideShopCheckbox.checked);
  983. }
  984. },
  985. hideGiftControlFunc = () => {
  986. let dom = document.getElementsByClassName('gift-control-section')[0];
  987. if (dom) {
  988. noneDisplay(dom, hideGiftControlCheckbox.checked);
  989. }
  990.  
  991. dom = document.getElementById('web-player__bottom-bar__container');
  992. if (dom) {
  993. noneDisplay(dom, hideGiftControlCheckbox.checked);
  994. }
  995.  
  996. dom = document.getElementsByTagName('video');
  997. for (let i = 0; i < dom.length; i++) {
  998. if (!dom[i]) {
  999. return;
  1000. }
  1001. if (hideGiftControlCheckbox.checked) {
  1002. dom[i].style.setProperty('height', '100%');
  1003. }
  1004. else if (document.body.classList.contains('player-full-win') || document.body.classList.contains('fullscreen-fix')) {
  1005. dom[i].style.setProperty('height', 'calc(100% - 114px)');
  1006. }
  1007. }
  1008. },
  1009. hideRoomFeedFunc = () => {
  1010. let dom = document.getElementsByClassName('room-feed')[0];
  1011. if (dom) {
  1012. noneDisplay(dom, hideRoomFeedCheckbox.checked);
  1013. }
  1014. dom = document.getElementsByClassName('flip-view p-relative')[0];
  1015. if (dom) {
  1016. noneDisplay(dom, hideRoomFeedCheckbox.checked);
  1017. }
  1018. },
  1019. hideRoomInfoFunc = () => {
  1020. let dom = document.getElementsByClassName('room-info-ctnr')[0];
  1021. if (dom) {
  1022. noneDisplay(dom, hideRoomInfoCheckbox.checked);
  1023. }
  1024. },
  1025. hideNoticeFunc = () => {
  1026. let dom = document.getElementsByClassName('right-container')[0];
  1027. if (dom) {
  1028. dom.style.setProperty('min-height', 'auto');
  1029. noneDisplay(dom, hideNoticeCheckbox.checked);
  1030. }
  1031. },
  1032. hideFooterFunc = () => {
  1033. let dom = document.getElementById('link-footer-vm');
  1034. if (dom) {
  1035. noneDisplay(dom, hideFooterCheckbox.checked);
  1036. }
  1037. },
  1038. hidePrivacyFunc = () => {
  1039. if (hidePrivacyCheckbox.checked) {
  1040. let dom = document.createElement('style');
  1041. dom.id = 'hidePrivacyDialog';
  1042. dom.setAttribute('type', 'text/css');
  1043. dom.innerHTML = '.privacy-dialog{display:none !important;}';
  1044. document.head.appendChild(dom);
  1045. }
  1046. else {
  1047. let dom = document.getElementById('hidePrivacyDialog');
  1048. if (dom) {
  1049. dom.remove();
  1050. }
  1051. }
  1052. },
  1053. hideRoomStatusFunc = () => {
  1054. let dom = document.getElementsByClassName('web-player-icon-roomStatus')[0];
  1055. if (dom) {
  1056. noneDisplay(dom, hideRoomStatusCheckbox.checked);
  1057. }
  1058. },
  1059. hideBusinessFunc = () => {
  1060. let dom = document.getElementById('businessContainerElement');
  1061. if (dom) {
  1062. noneDisplay(dom, hideBusinessCheckbox.checked);
  1063. }
  1064. },
  1065. // 适配Bilibili直播自动追帧样式
  1066. adaptBililiveSeeker = () => {
  1067. let dom = document.getElementById('playback-rate-title');
  1068. if (dom) {
  1069. noneDisplay(dom, true);
  1070. dom.parentElement.style.removeProperty('padding-bottom');
  1071. }
  1072.  
  1073. dom = document.getElementById('playback-rate-username');
  1074. if (dom) {
  1075. dom.style.removeProperty('display');
  1076. }
  1077. },
  1078. hideRankListFunc = () => {
  1079. let lower = document.getElementsByClassName('lower-row')[0];
  1080. if (!lower) {
  1081. return;
  1082. }
  1083.  
  1084. let dom = lower.getElementsByClassName('right-ctnr')[0]
  1085. if (dom) {
  1086. noneDisplay(dom, hideRankListCheckbox.checked);
  1087. let t = workerTimer.setTimeout(() => {
  1088. workerTimer.clearTimeout(t);
  1089. t = null;
  1090. adaptBililiveSeeker();
  1091. }, 100);
  1092. }
  1093. },
  1094. showLiveAreaFunc = () => {
  1095. let dom = document.getElementsByClassName('live-area')[0];
  1096. if (dom) {
  1097. blockDisplay(dom, showLiveAreaCheckbox.checked);
  1098. adaptBililiveSeeker();
  1099. }
  1100. },
  1101. lotteryFunc = () => {
  1102. window.localStorage.setItem(lotteryChecked, lotteryCheckbox.checked);
  1103. let dom = document.getElementById('hesitationCheckboxDiv');
  1104. if (dom) {
  1105. noneDisplay(dom, !lotteryCheckbox.checked)
  1106. }
  1107. },
  1108. closeLotteryFunc = () => {
  1109. window.localStorage.setItem(closeLotteryChecked, closeLotteryCheckbox.checked);
  1110. },
  1111. hesitationFunc = () => {
  1112. window.localStorage.setItem(hesitationChecked, hesitationCheckbox.checked);
  1113. window.localStorage.setItem(hesitationExpiry, hesitateInput.value);
  1114. },
  1115. setPublicFunc = () => {},
  1116. usePublicFunc = () => {
  1117. let obj = null;
  1118. if (usePublicCheckbox.checked) {
  1119. obj = getGmValue(baseInfo.default, null);
  1120. }
  1121. else {
  1122. obj = source;
  1123. }
  1124. if (obj) {
  1125. setSource(obj);
  1126. }
  1127. },
  1128. clickLikeBtn = () => {
  1129. let dom = document.getElementsByClassName('like-btn')[0];
  1130. if (dom) {
  1131. dom.click();
  1132. // console.log(`===> 【${new Date().toLocaleString()}】点击一次点赞按钮`);
  1133. }
  1134. },
  1135. autoLikeFunc = () => {
  1136. if (autoLikeCheckbox.checked) {
  1137. if (autoLikeTimer) {
  1138. return;
  1139. }
  1140.  
  1141. clickLikeBtn();
  1142. // console.log(`===> 开启自动点赞功能【${new Date().toLocaleString()}】`);
  1143. autoLikeTimer = workerTimer.setInterval(() => {
  1144. let rdTimeout = Math.floor(Math.random() * 15000);
  1145. if (1000 > rdTimeout) {
  1146. // console.log(`===> 【${new Date().toLocaleString()}】立刻点击点赞按钮`);
  1147. clickLikeBtn();
  1148. }
  1149. else {
  1150. // console.log(`===> 【${new Date().toLocaleString()}】设置【${rdTimeout}】毫秒后点击点赞按钮`);
  1151. clickLikeBtnTimer = workerTimer.setTimeout(() => {
  1152. workerTimer.clearTimeout(clickLikeBtnTimer);
  1153. clickLikeBtnTimer = null;
  1154. clickLikeBtn();
  1155. }, rdTimeout);
  1156. }
  1157. }, 15e3);
  1158. }
  1159. else {
  1160. if (autoLikeTimer) {
  1161. workerTimer.clearInterval(autoLikeTimer);
  1162. autoLikeTimer = null;
  1163. // console.log(`===> 关闭自动点赞功能`);
  1164. }
  1165. if (clickLikeBtnTimer) {
  1166. workerTimer.clearTimeout(clickLikeBtnTimer);
  1167. clickLikeBtnTimer = null;
  1168. // console.log(`===> 关闭超时点击点赞按钮功能`);
  1169. }
  1170. }
  1171. },
  1172. clickPlay = () => {
  1173. // let dom = document.getElementsByClassName('_tip-btn_6f52f')[0];
  1174. // if (dom) {
  1175. // dom.click();
  1176. // }
  1177.  
  1178. // dom = document.getElementsByClassName('_tip-text_6f52f')[0];
  1179. // if (dom) {
  1180. // dom.click();
  1181. // }
  1182. },
  1183. autoPlay = () => {
  1184. let t = workerTimer.setTimeout(() => {
  1185. workerTimer.clearTimeout(t);
  1186. clickPlay();
  1187. t = workerTimer.setTimeout(() => {
  1188. workerTimer.clearTimeout(t);
  1189. t = null;
  1190. clickPlay();
  1191. }, 2e3);
  1192. }, 3e3);
  1193. },
  1194. noSleepFunc = () => {
  1195. if (noSleepCheckbox.checked) {
  1196. if (!noSleepTimer) {
  1197. console.log('===> 开启防休眠功能');
  1198. noSleepTimer = workerTimer.setInterval(() => {
  1199. noSleepTimeouter = workerTimer.setTimeout(() => {
  1200. workerTimer.clearTimeout(noSleepTimeouter);
  1201. document.body.dispatchEvent(new MouseEvent("mousemove", { bubbles: true }));
  1202. }, Math.random() * 3e3);
  1203. }, 17e3);
  1204. }
  1205. } else {
  1206. console.log('===> 关闭防休眠功能');
  1207. if (noSleepTimer) {
  1208. workerTimer.clearInterval(noSleepTimer);
  1209. noSleepTimer = null;
  1210. }
  1211. if (noSleepTimeouter) {
  1212. workerTimer.clearTimeout(noSleepTimeouter);
  1213. noSleepTimeouter = null;
  1214. }
  1215. }
  1216. },
  1217. biliMiniClose = () => {
  1218. if (!miniCloseTimer) {
  1219. let miniCloseCount = 3;
  1220. miniCloseTimer = workerTimer.setInterval(() => {
  1221. let mini_close = document.getElementsByClassName('bili-mini-close')[0];
  1222. if (!mini_close) {
  1223. if (0 >= --miniCloseCount) {
  1224. workerTimer.clearInterval(miniCloseTimer);
  1225. miniCloseTimer = null;
  1226. }
  1227.  
  1228. return;
  1229. }
  1230.  
  1231. mini_close.click();
  1232. workerTimer.clearInterval(miniCloseTimer);
  1233. miniCloseTimer = null;
  1234. }, 10e3);
  1235. }
  1236. },
  1237. closeLottery = delay => {
  1238. let btnClose = document.getElementsByClassName('close-btn bg-contain')[0];
  1239. if (btnClose) {
  1240. if (isNull(delay)) {
  1241. btnClose.click();
  1242. } else {
  1243. closeLotteryTimer = workerTimer.setTimeout(() => {
  1244. workerTimer.clearTimeout(closeLotteryTimer);
  1245. btnClose.click();
  1246. }, delay * 1000);
  1247. }
  1248. }
  1249. },
  1250. lottery = btn => {
  1251. if (!btn) {
  1252. console.warn('===> 没有抽奖按钮DOM');
  1253. return;
  1254. }
  1255. if ('false' === window.localStorage.getItem(lotteryChecked)) {
  1256. if ('true' === window.localStorage.getItem(closeLotteryChecked)) {
  1257. console.log('===> 不参与天选时刻抽奖,关闭弹窗');
  1258. closeLottery();
  1259. }
  1260.  
  1261. return;
  1262. }
  1263. if ('true' === window.localStorage.getItem(hesitationChecked)) {
  1264. let expiry = window.localStorage.getItem(hesitationExpiry);
  1265. expiry = isNull(expiry) || 0 >= expiry ? 10e4 : expiry * 1000;
  1266. expiry = Math.ceil(Math.random() * expiry);
  1267. // console.log(`===> 【${new Date().toLocaleString()}】随机时间【${expiry}】`);
  1268. let lotteryTimer = workerTimer.setTimeout(() => {
  1269. workerTimer.clearTimeout(lotteryTimer);
  1270. console.log(`===> ${new Date().toLocaleString()}】犹豫期过后自动参加抽奖`);
  1271. btn.click();
  1272. if ('true' === window.localStorage.getItem(closeLotteryChecked)) {
  1273. console.log('===> 参加成功,延迟关闭弹窗');
  1274. closeLottery(3);
  1275. }
  1276. }, expiry);
  1277. } else {
  1278. console.log('===> 立刻自动参加抽奖');
  1279. btn.click();
  1280. if ('true' === window.localStorage.getItem(closeLotteryChecked)) {
  1281. console.log('===> 参加成功,延迟关闭弹窗');
  1282. closeLottery(3);
  1283. }
  1284. }
  1285. },
  1286. listPlus = nodes => {
  1287. if (!nodes || 0 >= nodes.length) return;
  1288. Array.prototype.forEach.call(nodes, y => {
  1289. let aNode = y.firstChild;
  1290. if (!aNode) return;
  1291. let a_d2 = aNode.children[1];
  1292. if (!a_d2) return;
  1293. let a_d2_d2 = a_d2.children[1];
  1294. if (!a_d2_d2) return;
  1295. let a_d2_d2_d2 = a_d2_d2.children[1];
  1296. if (!a_d2_d2_d2) return;
  1297. let a_d2_d2_d2_d1 = a_d2_d2_d2.children[0];
  1298. if (!a_d2_d2_d2_d1) return;
  1299. aNode.title = a_d2_d2_d2_d1.textContent;
  1300. let a_d2_d1 = a_d2.children[0];
  1301. if (a_d2_d1) {
  1302. let a_d2_d1_last = a_d2_d1.lastChild;
  1303. if (a_d2_d1_last && a_d2_d1_last.style.display && 'none' == a_d2_d1_last.style.display) {
  1304. a_d2_d1_last.remove();
  1305. }
  1306. }
  1307. });
  1308. },
  1309. getConfig = () => {
  1310. let c = {};
  1311. if (baseInfo.config) {
  1312. c = getGmValue(baseInfo.config, {});
  1313. if (isNull(c.lottery)) {
  1314. c.lottery = false;
  1315. }
  1316. if (isNull(c.closeLottery)) {
  1317. c.closeLottery = false;
  1318. }
  1319. if (isNull(c.hesitation)) {
  1320. c.hesitation = false;
  1321. }
  1322. }
  1323.  
  1324. return c;
  1325. },
  1326. checkVersion = () => {
  1327. config = getConfig();
  1328. if (!config || !config.moduleVersion || !divUpdateInfo) {
  1329. return;
  1330. }
  1331. if (0 < compareVersion(config.moduleVersion, version)) {
  1332. divUpdateInfo.innerHTML = `<span class="update-info-text">有新版本,刷新网页进行更新</span>`;
  1333. let dom = document.getElementById('otherContainer');
  1334. if (dom) {
  1335. dom.style.fontSize = '18px';
  1336. dom.style.textAlign = 'center';
  1337. dom.appendChild(divUpdateInfo.cloneNode(true));
  1338. }
  1339. }
  1340. },
  1341. loadData = () => {
  1342. let obj = getGmValue(roomId, null),
  1343. key = roomId;
  1344. if (obj) {
  1345. if (obj.usePublic && baseInfo.default) {
  1346. let ps = getGmValue(baseInfo.default, null);
  1347. if (ps) {
  1348. obj.data1.values = ps.data1 ? ps.data1.values : obj.data1.values;
  1349. obj.data2.values = ps.data2 ? ps.data2.values : obj.data2.values;
  1350. obj.data3.values = ps.data3 ? ps.data3.values : obj.data3.values;
  1351. obj.data4.values = ps.data4 ? ps.data4.values : obj.data4.values;
  1352. obj.data5.values = ps.data5 ? ps.data5.values : obj.data5.values;
  1353. }
  1354. }
  1355. if (source.version === obj.version) {
  1356. source = {...source, ...obj};
  1357. }
  1358. else if (obj.version === 2) {
  1359. source.data1 = obj.data1;
  1360. source.data2 = obj.data2;
  1361. source.data3 = obj.data3;
  1362. source.data4 = obj.data4;
  1363. source.data5 = obj.data5;
  1364. setGmValue(key, source);
  1365. }
  1366. else {
  1367. source.data1.values = obj.data1 ? obj.data1.values : source.data1.values;
  1368. source.data2.values = obj.data2 ? obj.data2.values : source.data2.values;
  1369. source.data3.values = obj.data3 ? obj.data3.values : source.data3.values;
  1370. source.data4.values = obj.data4 ? obj.data4.values : source.data4.values;
  1371. source.data5.values = obj.data5 ? obj.data5.values : source.data5.values;
  1372. setGmValue(key, source);
  1373. }
  1374. }
  1375. config = getConfig();
  1376. signInput.value = isNull(config.signInText) ? '' : config.signInText;
  1377. hesitateInput.value = isNull(config.hesitationExpiry) ? '100' : config.hesitationExpiry;
  1378. setSource(source);
  1379. setOperationSetting();
  1380. initData();
  1381. },
  1382. closeWsHeartBeatTimer = () => workerTimer.clearInterval(wsHeartBeatTimer),
  1383. closeWsReconnectTimer = () => {
  1384. workerTimer.clearInterval(wsReconnectWsTimer);
  1385. wsReconnectWsTimer = null;
  1386. },
  1387. /* param
  1388. j 字符串
  1389. v 协议版本(
  1390. 0: 普通包 (正文不使用压缩)
  1391. 1: 心跳及认证包 (正文不使用压缩)
  1392. 2: 普通包 (正文使用 zlib 压缩)
  1393. 3: 普通包 (使用 brotli 压缩的多个带文件头的普通包)
  1394. t 操作码(封包类型)
  1395. 2: 心跳包
  1396. 3: 心跳包回复 (人气值)
  1397. 5: 普通包 (命令)
  1398. 7: 认证包
  1399. 8: 认证包回复
  1400. */
  1401. wsPacket = (j, v, t) => {
  1402. const en = textEncoder.encode(j),
  1403. headLen = 16,
  1404. packetLen = en.byteLength + headLen,
  1405. buff = new ArrayBuffer(packetLen),
  1406. view = new DataView(buff);
  1407. view.setUint32(0, packetLen);
  1408. view.setUint16(4, headLen);
  1409. view.setUint16(6, v);
  1410. view.setUint32(8, t);
  1411. view.setUint32(12, 1);
  1412. for(let i = 0; i < en.byteLength; i++) {
  1413. view.setUint8(16 + i, en[i]);
  1414. }
  1415.  
  1416. return buff;
  1417. },
  1418. wsUnpaket = (blob, callback) => {
  1419. const reader = new FileReader();
  1420. reader.onload = async e => {
  1421. const aBuff = e.target.result, //ArrayBuffer对象
  1422. abuffView = new DataView(aBuff); //视图
  1423. let offset = 0, result = [];
  1424. while(offset < aBuff.byteLength) { //数据提取
  1425. let decompressedData;
  1426. const packetLen = abuffView.getUint32(offset + 0),
  1427. headLen = abuffView.getUint16(offset + 4),
  1428. packetVer = abuffView.getUint16(offset + 6),
  1429. packetType = abuffView.getUint32(offset + 8),
  1430. seq = abuffView.getUint32(12);
  1431. switch(packetVer) { //解压数据
  1432. case 3: //brotli压缩
  1433. const brotli = new Uint8Array(aBuff, offset + headLen, packetLen - headLen);
  1434. if (baseInfo.brotli) {
  1435. decompressedData = baseInfo.brotli.BrotliDecode(brotli.buffer);
  1436. transferData(decompressedData, result);
  1437. }
  1438. else {
  1439. console.warn(`===> Brotli解压模块未空`);
  1440. }
  1441. break;
  1442. case 2: //zlib压缩
  1443. const zlib = new Uint8Array(aBuff, offset + headLen, packetLen - headLen);
  1444. try {
  1445. decompressedData = pako.inflate(zlib);
  1446. } catch(error) {
  1447. console.error(`===> pako.inflate解压出错`, error);
  1448. console.log(`===> zlib解压失败数据【${zlib}】`);
  1449. decompressedData = zlib;
  1450. }
  1451.  
  1452. transferData(decompressedData, result);
  1453. break;
  1454. default:
  1455. const packet = {};
  1456. packet.plen = packetLen;
  1457. packet.hlen = headLen;
  1458. packet.ver = packetVer;
  1459. packet.type = packetType;
  1460. packet.seq = seq;
  1461. if (packetType == 3){ //获取人气值
  1462. packet.body = (new DataView(aBuff, offset + headLen, packetLen - headLen)).getUint32(0); //若入参为dataArray.buffer,会返回整段buff的视图,而不是截取后的视图
  1463. }else{
  1464. const dataArray = new Uint8Array(aBuff, offset + headLen, packetLen - headLen);
  1465. packet.body = textDecoder.decode(dataArray); //utf-8格式数据解码,获得字符串
  1466. }
  1467.  
  1468. result.push(packet); //数据打包后传入数组
  1469. }
  1470.  
  1471. offset += packetLen;
  1472. }
  1473.  
  1474. callback(result); //数据后续处理
  1475. };
  1476.  
  1477. reader.readAsArrayBuffer(blob); //读取服务器传来的数据转换为ArrayBuffer
  1478. },
  1479. transferData = (arrayBuff, result) => {
  1480. if(!arrayBuff) {
  1481. return;
  1482. }
  1483. let offset = 0;
  1484. const buffView = new DataView(arrayBuff);
  1485. while(offset < arrayBuff.byteLength){ //解压后数据提取
  1486. const packetLen = buffView.getUint32(offset + 0),
  1487. headLen = buffView.getUint16(offset + 4),
  1488. packet = {};
  1489. packet.plen = packetLen;
  1490. packet.hlen = headLen;
  1491. packet.ver = buffView.getUint16(offset + 6);
  1492. packet.type = buffView.getUint32(offset + 8);
  1493. packet.seq = buffView.getUint32(12);
  1494. const dataArray = new Uint8Array(arrayBuff, offset + headLen, packetLen - headLen);
  1495. packet.body = textDecoder.decode(dataArray); //utf-8格式数据解码,获得字符串
  1496. result.push(packet); //数据打包后传入数组
  1497. offset += packetLen;
  1498. }
  1499. },
  1500. handleWsPacket = list => {
  1501. if (!list || 1 > list.length) {
  1502. return;
  1503. }
  1504.  
  1505. list.forEach(packet => {
  1506. switch (packet.type) {
  1507. // 认证包回复
  1508. case 8:
  1509. eventTarget.dispatchEvent(new CustomEvent(eventTypeEnum.authReply, {detail: JSON.parse(packet.body)}));
  1510. break;
  1511. // 心跳包回复(人气值)
  1512. case 3:
  1513. eventTarget.dispatchEvent(new CustomEvent(eventTypeEnum.heartBeatReply, {detail: packet.body}));
  1514. break;
  1515. // 普通包(命令)
  1516. case 5:
  1517. const msg = JSON.parse(packet.body);
  1518. eventTarget.dispatchEvent(new CustomEvent(msg.cmd, {detail: msg}));
  1519. if (!wsCmds.includes(msg.cmd)) {
  1520. wsCmds.push(msg.cmd);
  1521. }
  1522. break;
  1523. default:
  1524. console.log(`===> 没对应的操作码【${JSON.stringify(packet)}】`);
  1525. }
  1526. });
  1527. },
  1528. bingWsMsgEvent = () => {
  1529. // 认证包回复
  1530. onEvent(eventTypeEnum.authReply, d => {
  1531. if (0 == d.code) {
  1532. closeWsReconnectTimer();
  1533. console.log(`===> 成功加入房间`);
  1534. }
  1535. else {
  1536. console.warn(`===> 认证失败`);
  1537. }
  1538. });
  1539. // 心跳包回复(人气值)
  1540. onEvent(eventTypeEnum.heartBeatReply, d => {
  1541. closeWsReconnectTimer();
  1542. console.log(`===> 人气:${d}`);
  1543. });
  1544. // 弹幕消息
  1545. onEvent(eventTypeEnum.danmuMsg, d => {
  1546. console.log(`===> ${d.info[2][1]}: ${d.info[1]}`);
  1547. });
  1548. // 主播准备中(0 未轮播;1 正在轮播)
  1549. onEvent(eventTypeEnum.preparing, d => {
  1550. console.log(`===> 直播间【${d.roomid}】状态【${d.round}】`);
  1551. });
  1552. // 直播开始
  1553. onEvent(eventTypeEnum.live, d => {
  1554. console.log(`===> 直播间【${d.roomid}】在【${new Date(d.live_time).toLocaleString()}】开始直播`);
  1555. });
  1556. // 直播间信息更改
  1557. onEvent(eventTypeEnum.roomChange, e => {
  1558. console.log(`===> 直播信息变更,标题【${d.data.title}】,分区【${d.data.area_name}】,上级分区【${d.data.parent_area_name}】`);
  1559. });
  1560. // 下播的直播间
  1561. onEvent(eventTypeEnum.stopLiveRoomList, d => {
  1562. console.log(`===> 当前直播间是否下播【${d.data.room_id_list.includes(roomId)}】`);
  1563. });
  1564. // 切断
  1565. onEvent(eventTypeEnum.cutOff, d => {
  1566. console.log(`===> 直播间【${d.roomid}】已被切断【${d.msg}】`);
  1567. });
  1568. // 天选时刻开始
  1569. onEvent(eventTypeEnum.anchorLotStart, d => {
  1570. console.log(`===> 直播间【${d.data.room_id}】在【${new Date(d.data.current_time).toLocaleDateString()}】开始天选时刻抽奖,id${d.data.id};max_time${d.data.max_time};danmu${d.data.danmu};time${d.data.time}`);
  1571. });
  1572. // 天选时刻结束
  1573. onEvent(eventTypeEnum.anchorLotEnd, d => {
  1574. console.log(`===> 天选时刻结束【${JSON.stringify(d)}】`);
  1575. });
  1576. // 重连直播间
  1577. onEvent(eventTypeEnum.reenterLiveRoom, d => {
  1578. console.log(`===> 重进直播间【${JSON.stringify(d)}】`);
  1579. });
  1580. },
  1581. connectWS = () => {
  1582. if (wsHostIndex < 0) {
  1583. wsHostIndex = baseInfo?.wsHosts.length - 1;
  1584. }
  1585. console.log(`===> 开始进行WS连接`);
  1586. ws = new WebSocket(`wss://${baseInfo?.wsHosts[wsHostIndex].host}:${baseInfo?.wsHosts[wsHostIndex].wss_port}/sub`);
  1587. ws.onopen = event => {
  1588. console.log(`===> WS连接成功,准备发认证包`);
  1589. const o = {
  1590. "uid": getUid() || 0,
  1591. "roomid": 0 < getRid() ? getRid() : roomId,
  1592. "protover": 3,
  1593. "buvid": getCookie('buvid3'),
  1594. "platform": "web",
  1595. "type": 2,
  1596. "key": baseInfo?.wsToken
  1597. };
  1598. const json = wsAuth || JSON.stringify(o);
  1599. console.log(`===> 序列化认证包【${json}】`);
  1600. ws.send(wsPacket(json, 1, 7));
  1601. console.log(`===> 认证包已经发送`);
  1602. };
  1603. ws.onmessage = event => wsUnpaket(event.data, handleWsPacket);
  1604. ws.onclose = event => {
  1605. closeWsHeartBeatTimer();
  1606. ws = null;
  1607. console.warn(`===> WS连接已关闭`);
  1608. };
  1609. ws.onerror = error => console.error('===> WebSocket error: ', error);
  1610. },
  1611. heartBeatWS = () => {
  1612. wsHeartBeatTimer = workerTimer.setInterval(() => {
  1613. if (!ws) {
  1614. closeWsHeartBeatTimer();
  1615. return;
  1616. }
  1617.  
  1618. console.log(`===> 准备发送心跳包`);
  1619. ws.send(wsPacket('', 1, 2));
  1620. console.log(`===> 心跳包已经发送`);
  1621. reconnectWS();
  1622. }, 30e3);
  1623. },
  1624. initWS = async () => {
  1625. if (ws) {
  1626. console.warn(`===> WS已初始化`);
  1627. return;
  1628. }
  1629. if (isNull(baseInfo?.wsToken)) {
  1630. console.warn(`===> WS token为空`);
  1631. return;
  1632. }
  1633. if (!baseInfo?.wsHosts || 1 > baseInfo?.wsHosts.length) {
  1634. console.warn(`===> WS host list为空`);
  1635. return;
  1636. }
  1637. connectWS();
  1638. heartBeatWS();
  1639. },
  1640. reconnectWS = () => {
  1641. if (wsReconnectWsTimer) {
  1642. return;
  1643. }
  1644.  
  1645. console.log(`===> 启动重连定时器`);
  1646. wsReconnectWsTimer = workerTimer.setInterval(() => {
  1647. if (ws) {
  1648. console.warn(`===> 心跳包响应超时,进行WS关闭操作`);
  1649. ws.close();
  1650. }
  1651. console.log(`===> 尝试WS重连`);
  1652. --wsHostIndex;
  1653. --wsConnectCount;
  1654. initWS();
  1655. }, 65e3);
  1656. },
  1657. initSettingPanel = (div, isLogin) => {
  1658. let settingPanel = document.getElementById('danmu-setting-panel');
  1659. if (div && !settingPanel) {
  1660. // console.log('===> 进行面板初始化');
  1661. let btnSend = document.getElementsByClassName('bl-button bl-button--primary')[0];
  1662. if (btnSend) {
  1663. buildPanel();
  1664. btnStart(btnSend);
  1665. if (isLogin) {
  1666. dmButtonSend.style.marginTop = '4px';
  1667. dmButtonSend.style.marginLeft = '30px';
  1668. btnSend.style.marginLeft = '30px';
  1669. div.appendChild(dmButtonSend);
  1670. div.parentNode.insertBefore(btnSetting(), div);
  1671. }
  1672. else {
  1673. let funcDiv = document.createElement('div');
  1674. funcDiv.style.position = 'absolute';
  1675. funcDiv.appendChild(dmButtonSend);
  1676. funcDiv.appendChild(btnSetting());
  1677. div.appendChild(funcDiv);
  1678. // bgcolor = window.getComputedStyle(btnSend).getPropertyValue('background-color');
  1679. // dmButtonSend.style.setProperty('background', bgcolor);
  1680. // dmButtonSend.style.setProperty('--color', bgcolor.replace(')', ', 0.8)'));
  1681. }
  1682. bingWsMsgEvent();
  1683. // initWS();
  1684. loadData();
  1685. // console.log('===> 面板初始化完成');
  1686. } else {
  1687. console.warn('===> 发送按钮丢失');
  1688. return false;
  1689. }
  1690. }
  1691.  
  1692. return true;
  1693. },
  1694. main = (div, isLogin) => {
  1695. waiters[waiters.length] = workerTimer.setInterval(() => {
  1696. if (initSettingPanel(div, isLogin)) {
  1697. clearWaiters();
  1698. } else {
  1699. --waitCount;
  1700. if (0 >= waitCount) {
  1701. clearWaiters();
  1702. console.log('===> 创建面板失败,停止初始化');
  1703. }
  1704. }
  1705. }, 1.5e3);
  1706. },
  1707. PluginBtn = (clazz, isLogin) => {
  1708. let div = document.getElementsByClassName(clazz)[0];
  1709. if (div) {
  1710. main(div, isLogin);
  1711. } else {
  1712. let count = 0;
  1713. divSendBtnTimer = workerTimer.setInterval(() => {
  1714. div = document.getElementsByClassName(clazz)[0];
  1715. if (div) {
  1716. workerTimer.clearInterval(divSendBtnTimer);
  1717. main(div, isLogin);
  1718. } else if (count++ >= 10) {
  1719. workerTimer.clearInterval(divSendBtnTimer);
  1720. // console.log(`===> 页面【${window.location.href}】没有定位位置`);
  1721. }
  1722. }, 1e3);
  1723. }
  1724. },
  1725. PluginLogout = () => PluginBtn('bottom-actions p-relative', false),
  1726. PluginLogin = () => PluginBtn('right-actions border-box', true),
  1727. PluginLottery = () => {
  1728. let btn = document.getElementsByClassName('particitation-btn')[0];
  1729. if (btn) {
  1730. lottery(btn);
  1731. } else {
  1732. btnLotteryTimer = workerTimer.setTimeout(() => {
  1733. workerTimer.clearTimeout(btnLotteryTimer);
  1734. btn = document.getElementsByClassName('particitation-btn')[0];
  1735. if (btn) {
  1736. lottery(btn);
  1737. }
  1738. }, 2e3);
  1739. }
  1740. },
  1741. PluginListPlus = () => {
  1742. let listTimer = workerTimer.setTimeout(() => {
  1743. workerTimer.clearTimeout(listTimer);
  1744. let obsConfig = {childList: true},
  1745. tags = ['all__card-list-ctnr', 'all__special-area-recommend-list-ctnr'];
  1746. tags.forEach(x => {
  1747. let dom = document.getElementsByClassName(x)[0];
  1748. if (!dom) return;
  1749. Array.prototype.forEach.call(dom.children, y => {
  1750. if (/^index_/i.test(y.className)) {
  1751. listPlus(y.children);
  1752. let obs = new MutationObserver(mrs => {
  1753. if (!mrs || 0 >= mrs.length) return;
  1754. Array.prototype.forEach.call(mrs, z => listPlus(z.addedNodes));
  1755. });
  1756. obs.observe(y, obsConfig);
  1757. }
  1758. });
  1759. });
  1760. }, 0.5e3);
  1761. },
  1762. debug = () => {debugger;},
  1763. runStart = () => {
  1764. PluginLottery();
  1765. PluginListPlus();
  1766. PluginLogout();
  1767. PluginLogin();
  1768. }
  1769. , printWsInfos = () => {
  1770. console.log(`===> TrueRoomId: ${getRid()}; ShortRoomId: ${roomId}`);
  1771. console.log(`==> wsConnectCount: ${wsConnectCount}`);
  1772. console.log(`===> bvuid: ${getCookie('buvid3')}`)
  1773. console.log(`===> token: ${baseInfo?.wsToken}`);
  1774. console.log(baseInfo?.wsHosts);
  1775. console.info(wsCmds);
  1776. },
  1777. runWS = () => initWS(),
  1778. stopWS = () => {
  1779. closeWsReconnectTimer();
  1780. if (ws) {
  1781. console.log(`===> 进行WS关闭操作`);
  1782. ws.close();
  1783. }
  1784. },
  1785. setWsAuth = auth => wsAuth = auth,
  1786. setWsHostIndex = i => wsHostIndex = i,
  1787. getWsInfo = async () => {
  1788. console.log(`===> 开始获取WS info`);
  1789. const u = 'https://api.live.bilibili.com/xlive/web-room/v1/index/getDanmuInfo?id=#rid#&type=0';
  1790. const resp = await fetch(u.replace('#rid#', roomId), {method: 'GET', cache: 'no-store', credentials: 'include'});
  1791. if (!resp.ok) {
  1792. console.warn(`===> WS host信息请求不成功`);
  1793. return;
  1794. }
  1795. const obj = await resp.json();
  1796. if (0 !== obj?.code) {
  1797. console.warn(`===> 获取WS host失败【${obj?.message}】`);
  1798. return;
  1799. }
  1800. if (!obj?.data?.host_list || 1 > obj?.data?.host_list.length) {
  1801. console.warn(`===> WS host信息为空`);
  1802. return;
  1803. }
  1804. console.log(`===> WS token = ${obj.data.token}`);
  1805. }
  1806. ;
  1807.  
  1808. initCss();
  1809. initScript();
  1810.  
  1811. window.debug = debug;
  1812. window.runWS = runWS;
  1813. window.stopWS = stopWS;
  1814. window.printWsInfos = printWsInfos;
  1815. window.setWsAuth = setWsAuth;
  1816. window.setWsHostIndex = setWsHostIndex;
  1817. window.getWsInfo = getWsInfo;
  1818.  
  1819. window.runStart = runStart;
  1820. window.arrayInfo = arrayInfo;
  1821. window.setGmNotice = setGmNotice;
  1822. window.setGmGetValue = setGmGetValue;
  1823. window.setGmSetValue = setGmSetValue;
  1824. window.setGmDelValue = setGmDelValue;
  1825. window.setBaseInfo = setBaseInfo;
  1826. window.checkVersion = checkVersion;
  1827. })();