b-live-random-send-test

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

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

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

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