Weibo Huati Check-in

超级话题集中签到

当前为 2018-04-09 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Weibo Huati Check-in
  3. // @description 超级话题集中签到
  4. // @namespace https://greasyfork.org/users/10290
  5. // @version 0.4.2018040912
  6. // @author xyau
  7. // @match http*://*.weibo.com/*
  8. // @match http*://weibo.com/*
  9. // @icon https://n.sinaimg.cn/photo/5b5e52aa/20160628/supertopic_top_area_big_icon_default.png
  10. // @grant GM_getValue
  11. // @grant GM_setValue
  12. // @grant GM_deleteValue
  13. // @grant GM_xmlhttpRequest
  14. // @connect m.weibo.cn
  15. // @connect login.sina.com.cn
  16. // @connect passport.weibo.cn
  17. // @connect weibo.com
  18. // ==/UserScript==
  19.  
  20. window.addEventListener('unload', () => console.groupEnd());
  21. window.addEventListener('load', () => {
  22. try {
  23. if ($CONFIG && '1' !== $CONFIG.islogin) {
  24. console.warn('尚未登录微博');
  25. return;
  26. }
  27. /**
  28. * @const {object} DEFAULT_CONFIG 默认设置
  29. * @const {boolean} DEFAULT_CONFIG.autoCheckin 自动签到
  30. * @const {string} DEFAULT_CONFIG.checkinMode 签到模式
  31. * @const {boolean} DEFAULT_CONFIG.checkNormal 普话签到
  32. * @const {boolean} DEFAULT_CONFIG.autoCheckState 自动查询状态
  33. * @const {boolean} DEFAULT_CONFIG.openDetail 展开详情
  34. * @const {int} DEFAULT_CONFIG.maxHeight 详情限高(px)
  35. * @const {int} DEFAULT_CONFIG.timeout 操作超时(ms)
  36. * @const {int} DEFAULT_CONFIG.retry 重试次数
  37. * @const {int} DEFAULT_CONFIG.delay 操作延时(ms)
  38. */
  39. const DEFAULT_CONFIG = Object.freeze({
  40. autoCheckin: true,
  41. checkinMode: 'followList',
  42. checkNormal: true,
  43. autoCheckState: false,
  44. openDetail: true,
  45. maxHeight: 360,
  46. timeout: 5000,
  47. retry: 5,
  48. delay: 0,
  49. }),
  50.  
  51. /**
  52. * @const {object} USER 当前用户
  53. * @const {string} USER.UID 用户ID
  54. * @const {string} USER.NICK 用户昵称
  55. */
  56. USER = Object.freeze({
  57. UID: $CONFIG.uid,
  58. NICK: $CONFIG.nick,
  59. });
  60. /* @global {string} 记录名称 */
  61. var logName, checkinInfo;//, configForm;
  62.  
  63. /**
  64. * @global {object} log 签到记录
  65. * @global {object[]} log.已签 已签话题列表
  66. * @global {object[]} log.待签 待签话题列表
  67. * @global {object} log.异常 签到异常列表
  68. */
  69. let log = {},
  70.  
  71. /* @return {string} 当前东八区日期 */
  72. getDate = () => new Date(new Date().getTime() + 288e5).toJSON().substr(0, 10).replace(/-0?/g, '/'),
  73.  
  74. /* @global {Task|null} currentTask 当前 xhr 任务 */
  75. currentTask = null,
  76.  
  77. /**
  78. * 任务构造,初始化通用 xhr 参数
  79. * @constructor
  80. * @param {string} name 任务名称
  81. * @param {object} options 附加 xhr 参数
  82. * @param {function} load 成功加载函数
  83. * @param {function} retry 重试函数
  84. * @param {function} [retryButton=] 重试按钮函数
  85. */
  86. Task = this.Task || function (name, options, load, retry, retryButton) {
  87. this.name = name;
  88. this.onerror = function(errorType='timeout') {
  89. initLog(name, 0);
  90. log[name] += 1;
  91.  
  92. if (errorType != 'timeout') {
  93. console.error(`${name}异常`);
  94. console.info(this);
  95. }
  96.  
  97. if (log[name] < config.retry + 1) {
  98. setStatus(name + (errorType === 'timeout' ? `超过${config.timeout / 1e3}秒` : '异常') + `,第${log[name]}次重试…`);
  99. retry();
  100. } else {
  101. setStatus(`${name}超时/异常${log[name]}次,停止自动重试`);
  102.  
  103. if (retryButton)
  104. retryButton();
  105. else
  106. clearTask();
  107. }
  108. };
  109. this.xhrConfig = {
  110. synchoronous: false,
  111. timeout: config.timeout,
  112. onloadstart: () => {
  113. currentTask = this;
  114.  
  115. if (!log.hasOwnProperty(name))
  116. setStatus(`${name}…`);
  117. if (retryButton) {
  118. /* 跳过按钮 */
  119. let skipHuati = document.createElement('a');
  120. skipHuati.classList.add('S_ficon');
  121. skipHuati.onclick = () => {
  122. this.xhr.abort();
  123. retryButton();
  124. skipHuati.remove();
  125. };
  126. skipHuati.innerText = '[跳过]';
  127. checkinInfo.querySelector('.status').appendChild(skipHuati);
  128. }
  129.  
  130. },
  131. onload: (xhr) => {
  132. if (xhr.finalUrl.includes('login')) {
  133. xhr.timeout = 0;
  134. /* 登录跳转 */
  135. let loginJump = GM_xmlhttpRequest({
  136. method: 'GET',
  137. synchronous: false,
  138. timeout: config.timeout,
  139. url: /url=&#39;([^']+)&#39;/.exec(xhr.responseText)[1],
  140. onloadstart: () => this.xhr = loginJump,
  141. onload: (xhr) => this.load(xhr),
  142. ontimeout: xhr.ontimeout,
  143. });
  144. }
  145. else
  146. this.load(xhr);
  147. },
  148. ontimeout: () => this.onerror(),
  149. };
  150.  
  151. Object.assign(this.xhrConfig, options);
  152.  
  153. this.load = (xhr) => setTimeout(load(xhr), config.delay);
  154. this.xhr = GM_xmlhttpRequest(this.xhrConfig);
  155. },
  156.  
  157. clearTask = function() {
  158. currentTask = null;
  159. document.querySelector('.checkin .close').title = '关闭';
  160. },
  161.  
  162. initLog = function(key, initialValue) {
  163. if (!log.hasOwnProperty(key))
  164. log[key] = initialValue;
  165. },
  166.  
  167. /**
  168. * see DEFAULT_CONFIG
  169. * @global {object} config 脚本设置
  170. * @global {object} lastCheckin 上次签到记录
  171. * @global {array} whitelist 话题白名单
  172. */
  173. config = Object.assign(Object.assign({},DEFAULT_CONFIG), JSON.parse(GM_getValue(`config${USER.UID}`, '{}'))),
  174. lastCheckin = JSON.parse(GM_getValue(`lastCheckin${USER.UID}`, '{}')),
  175. whitelist = JSON.parse(GM_getValue(`whitelist${USER.UID}`, '[]')),
  176.  
  177. initCheckinBtn = function() {
  178. if (config.autoCheckState && logName === '微博超话签到')
  179. checkState();
  180. if (config.openDetail && document.querySelector('.checkin .detail'))
  181. document.querySelector('.checkin .done').parentNode.setAttribute('open', '');
  182. checkinBtn.style = 'cursor: pointer';
  183. Array.from(checkinBtn.querySelectorAll('em')).forEach((em) => {em.removeAttribute('style');});
  184. checkinBtn.querySelector('em:last-child').innerText = '超话签到';
  185. checkinBtn.title = '左击开始签到/右击配置脚本';
  186. if (logName)
  187. console.groupEnd();
  188. logName = document.querySelector('.checkin.config') ? '微博超话签到设置' : null;
  189. },
  190.  
  191. /* @param {string} operationName 操作名称 */
  192. alterCheckinBtn = function(operationName) {
  193. checkinBtn.style.pointerEvents = 'none';
  194. Array.from(checkinBtn.querySelectorAll('em')).forEach((em) => {em.style.color = '#fa7d3c';});
  195. checkinBtn.querySelector('em:last-child').innerText = `${operationName}中…`;
  196. document.querySelector('.checkin .close').title = '中止';
  197. logName = '微博超话签到' + (operationName !== '签到' ? operationName : '');
  198. if (!logName.includes('查询') || operationName !== '设置')
  199. console.group(logName);
  200. },
  201.  
  202. /* @param {boolean} auto 自动开始*/
  203. huatiCheckin = function(auto=true) {
  204. const date = getDate();
  205.  
  206. /**
  207. * 获取关注话题列表
  208. * @param {object[]} [huatiList=[]] 关注话题列表
  209. * @param {string} huatiList[].name 名称
  210. * @param {string} huatiList[].hash 编号
  211. * @param {int|null} huatiList[].level 超话等级
  212. * @param {boolean} huatiList[].checked 超话已签
  213. * @param {object} [since_id=''] 列表起始
  214. * @param {string} [type='super'] 超话或普话, 'super'/'normal'
  215. */
  216. let getFollowList = function(huatiList=[], since_id='', type='super') {
  217.  
  218. let getPage = new Task(
  219. `正在获取${type=='super'?'超级':'普通'}话题列表`,
  220. {
  221. method: 'GET',
  222. url: `https://m.weibo.cn/api/container/getIndex?containerid=100803_-_page_my_follow_${type}&since_id=${since_id}`,
  223. },
  224. (xhr) => parsePage(xhr),
  225. () => getFollowList(huatiList, since_id, type)
  226. ),
  227.  
  228. parsePage = function(xhr) {
  229. let data = JSON.parse(xhr.responseText);
  230. // console.log(data);
  231.  
  232. if (!data.ok) {
  233. getPage.onerror('error');
  234. } else {
  235. let cards = data.data.cards.find(c => c.card_type_name.includes('follow'));
  236. cards.card_group.forEach(function(card) {
  237. if ([4,8].includes(+card.card_type)) {
  238. let huati = {
  239. name: (card.title_sub || card.desc).replace(/#(.*)#/,'$1'),
  240. level: null,
  241. checked: !!card.title_flag_pic,
  242. hash: null,
  243. element: null
  244. };
  245.  
  246. if (lastHuatiList && lastHuatiList.includes(huati.name)) {
  247. if (!todayChecked) {
  248. Object.assign(huati, log.待签.find((huati_) => huati_.name === huati.name));
  249. if (huati.checked)
  250. Object.assign(huati, log.待签.splice(log.待签.findIndex((huati_) => huati_.name === huati.name), 1).pop());
  251. } else {
  252. huati.hash = log.已签[huati.name];
  253. huati.element = document.getElementById(`_${huati.hash}`);
  254. }
  255. } else {
  256. huati.hash = /100808(\w+)&/.exec(card.scheme)[1];
  257. huati.element = initElement(huati.name, huati.hash);
  258. }
  259. huatiList.push(huati);
  260.  
  261. if (!lastHuatiList || !lastHuatiList.includes(huati.name) || !todayChecked) {
  262. if (huati.checked) {
  263. checkinInfo.querySelector('.done').appendChild(huati.element);
  264. initLog('已签', {});
  265. log.已签[huati.name] = huati.hash;
  266. } else {
  267. checkinInfo.querySelector('.toDo').appendChild(huati.element);
  268. initLog('待签', []);
  269. log.待签.push(huati);
  270. }
  271. }
  272. if (huati.level)
  273. setStatus(`Lv.${huati.level}`, huati.element);
  274. }
  275. });
  276. debugger;
  277. if (data.data.cardlistInfo.since_id)
  278. getFollowList(huatiList,data.data.cardlistInfo.since_id,type);
  279. else if (config.checkNormal && type == 'super')
  280. getFollowList(huatiList,'','normal');
  281. else {
  282. setStatus(`关注列表获取完毕,共${huatiList.length}个话题,` + (log.hasOwnProperty('待签') ? `${log.待签.length}个待签` : '全部已签'));
  283. console.table(huatiList);
  284. readyCheckin();
  285. }
  286. }
  287. };
  288. },
  289.  
  290. readyCheckin = function(){
  291. console.info(log);
  292.  
  293. if (log.hasOwnProperty('待签')) {
  294. if (config.autoCheckin)
  295. checkin(log.待签.shift());
  296. else {
  297. clearTask();
  298. /* 开始签到按钮 */
  299. let startCheckin = document.createElement('a');
  300. startCheckin.classList.add('S_ficon');
  301. startCheckin.onclick = () => checkin(log.待签.shift());
  302. startCheckin.innerText = '[开始签到]';
  303. checkinInfo.querySelector('.status').appendChild(startCheckin);
  304. }
  305. } else {
  306. clearTask();
  307. initCheckinBtn();
  308. }
  309. },
  310.  
  311. /* 获取话题编号 @param {array} list 话题名称列表 */
  312. getHash = function(list) {
  313. let name = list.shift(),
  314. huatiGetHash = new Task(
  315. `${name}话题信息获取`,
  316. {
  317. method: 'HEAD',
  318. url: `https://m.weibo.cn/api/container/getIndex?type=topic&value=${name}`,
  319. },
  320. (xhr) => {
  321. if (xhr.status === 200) {
  322. let regexp = /fid%3D100808(\w+)/g,
  323. hash = regexp.exec(xhr.responseHeaders.match(regexp).pop())[1];
  324. let element = initElement(name, hash);
  325. checkinInfo.querySelector('.toDo').append(element);
  326. initLog('待签', []);
  327. log.待签.push({name, hash, element});
  328. if (list.length)
  329. getHash(list);
  330. else {
  331. setStatus(`话题列表获取完毕,共${(log.hasOwnProperty('已签') ? Object.keys(log.已签).length : 0) + (log.hasOwnProperty('待签') ? log.待签.length : 0)}个话题` + (log.hasOwnProperty('待签') ? `${log.待签.length}个待签` : '全部已签'));
  332. readyCheckin();
  333. }
  334. }
  335. });
  336. },
  337.  
  338. getWhitelist = function() {
  339. let toDoList = whitelist.slice(0);
  340. if (!whitelist.length) {
  341. setStatus('尚未设置签到话题白名单!<a>[设置]</a>');
  342. checkinInfo.querySelector('.status').querySelector('a').onclick = () => {
  343. setupConfig();
  344. checkinInfo.querySelector('.whitelist .mode').click();
  345. checkinInfo.querySelector('.whitelist .edit').click();
  346. checkinInfo.querySelector('.whitelist .box').focus();
  347. };
  348. clearTask();
  349. initCheckinBtn();
  350. } else {
  351. if (lastHuatiList) {
  352. for (let name of lastHuatiList) {
  353. if (!whitelist.includes(name)) {
  354. if (!todayChecked) {
  355. let index = log.待签.findIndex((huati) => huati.name === name);
  356. log.待签[index].element.remove();
  357. log.待签.splice(index, 1);
  358. }
  359. } else
  360. toDoList.splice(toDoList.indexOf(name), 1);
  361. }
  362. }
  363. if (toDoList.length)
  364. getHash(toDoList);
  365. else {
  366. setStatus(`话题列表获取完毕,共${(log.hasOwnProperty('已签') ? Object.keys(log.已签).length : 0) + (log.hasOwnProperty('待签') ? log.待签.length : 0)}个话题` + (log.hasOwnProperty('待签') ? `${log.待签.length}个待签` : '全部已签'));
  367. readyCheckin();
  368. }
  369. }
  370. },
  371.  
  372. /**
  373. * 话题签到
  374. * @param {object} huati 话题,参见 {@link getFollowList#huatiList}
  375. * @param {boolean} checkinAll 签到全部话题
  376. */
  377. checkin = function(huati, checkinAll=true) {
  378. let huatiCheckin = new Task(
  379. `${huati.name}话题签到`,
  380. {
  381. method: 'GET',
  382. url: `/p/aj/general/button?api=http://i.huati.weibo.com/aj/super/checkin&id=100808${huati.hash}`,
  383. },
  384. (xhr) => {
  385. let data = JSON.parse(xhr.responseText),
  386. code = +data.code;
  387. // console.log(data);
  388.  
  389. switch (code) {
  390. case 100000:
  391. if (Object.keys(data.data).length)
  392. setStatus(
  393. /\d+/g.exec(data.data.alert_title) ?
  394. `签到第${/\d+/g.exec(data.data.alert_title)[0]}名,经验+${/\d+/g.exec(data.data.alert_subtitle)[0]}` :
  395. (console.log(JSON.stringify(data.data)), '签到成功'), huati.element, true);
  396. case 382004: {
  397. if (code !== 100000 || 0 === Object.keys(data.data).length)
  398. setStatus('已签', huati.element, true);
  399. checkinInfo.querySelector('.done').appendChild(huati.element);
  400. initLog('已签', {});
  401. log.已签[huati.name] = huati.hash;
  402. Object.assign(lastCheckin, {date, nick: USER.NICK});
  403. Object.assign(lastCheckin, log.已签);
  404. GM_setValue(`lastCheckin${USER.UID}`, JSON.stringify(lastCheckin));
  405. break;
  406. }
  407. default: {
  408. setStatus(data.msg, huati.element, true);
  409. initLog('异常', {});
  410. log.异常[huati.name] = {huati, code: data.code, msg: data.msg, xhr: xhr};
  411. huatiCheckin.onerror('error');
  412. }
  413. }
  414. if (checkinAll) {
  415. if (log.待签.length > 0)
  416. checkin(log.待签.shift());
  417. else {
  418. clearTask();
  419. setStatus(`${date} 签到完成`);
  420. checkinInfo.querySelector('.toDo').parentNode.removeAttribute('open');
  421. Object.assign(lastCheckin, {allChecked: true});
  422. GM_setValue(`lastCheckin${USER.UID}`, JSON.stringify(lastCheckin));
  423. console.info(log);
  424. initCheckinBtn();
  425. }
  426. }
  427. },
  428. () => checkin(huati, false),
  429. () => {
  430. log.待签.push(huati);
  431. if (log.待签.length > 0)
  432. checkin(log.待签.shift());
  433. else
  434. clearTask();
  435.  
  436. let retryHuati =document.createElement('a');
  437. retryHuati.classList.add('S_ficon');
  438. retryHuati.onclick = () => checkin(Object.assign({}, huati), false);
  439. retryHuati.innerText = '[重试]';
  440. setStatus(retryHuati, huati.element, true);
  441. }
  442. );
  443. },
  444.  
  445. initElement = function(name, hash) {
  446. /**
  447. * 文本限宽输出
  448. * @param {string} text 输入文本
  449. * @param {int} length 宽度限定
  450. * @return {string} 输出文本
  451. */
  452. let shorten = function(text, length) {
  453. let count = 0;
  454. for (let index in text) {
  455. let increment = /[\x00-\x7f]/.test(text[index]) ? 1 : 2;
  456. if (count + increment > length - 2)
  457. return `${text.substr(0, index)}…`;
  458. count += increment;
  459. }
  460. return text;
  461. },
  462. element = document.createElement('li');
  463. element.id = `_${hash}`;
  464. element.innerHTML = `<i class=order></i>.<a href=//weibo.com/p/100808${hash} target=_blank title=${name}>${shorten(name, 12)}</a><span class=info></span>`;
  465. return element;
  466. };
  467.  
  468. if (!lastCheckin.date || lastCheckin.date != date || !lastCheckin.allChecked || !auto) {
  469.  
  470. /* 设置信息展示界面 */
  471. var checkinCSS = document.querySelector('style.checkin') || document.createElement('style');
  472. checkinCSS.className = 'checkin';
  473. checkinCSS.type = 'text/css';
  474. checkinCSS.innerHTML = `.checkin.info {z-index:10000;position:fixed;left: 0px;bottom: 0px;min-width:320px;max-width: 640px;opacity: 0.9}.checkin.info .W_layer_title {border-top: solid 1px #fa7f40}.checkin .status {float: right;padding: 0 60px 0 10px}.checkin .more {right: 36px}.checkin.info .close {right: 12px}.checkin .detail {display: ${config.openDetail ? '' : 'none'};margin: 6px 12px;padding: 2px;max-height: ${config.maxHeight}px;overflow-y:auto;}${scrollbarStyle('.checkin .detail')}.checkin .detail summary {margin: 2px}.checkin .detail ol {column-count: 3}.checkin .detail li {line-height: 1.5}.checkin a {cursor: pointer}.checkin .info {float: right}.checkin .status ~ .W_ficon {position: absolute;bottom: 0px;font-size: 18px;}`;
  475. document.head.appendChild(checkinCSS);
  476.  
  477. //var
  478. checkinInfo = document.querySelector('.checkin.info') || document.createElement('div');
  479. //checkinInfo.id = 'checkinInfo';
  480. checkinInfo.className = 'W_layer checkin info';
  481. checkinInfo.innerHTML = `<div class=content><div><div class=detail><details open style=display:none><summary class="W_f14 W_fb">待签</summary><ol class=toDo></ol></details><details style=display:none><summary class="W_f14 W_fb">已签</summary><ol class=done></ol></details></div></div><div class=W_layer_title>${USER.NICK}<span class=status></span><a title=${config.openDetail ? '收起' :'详情'} class="W_ficon S_ficon more">${config.openDetail ? 'c' : 'd'}</a><a title=${currentTask ? '中止' : '关闭'} class="W_ficon S_ficon close">X</a></div></div>`;
  482. document.body.appendChild(checkinInfo);
  483.  
  484. alterCheckinBtn('签到');
  485.  
  486. checkinInfo.querySelector('.more').onclick = function() {
  487. if (this.innerText === 'd') {
  488. this.innerText = 'c';
  489. this.title = '收起';
  490. checkinInfo.querySelector('.detail').removeAttribute('style');
  491. } else {
  492. this.innerText = 'd';
  493. this.title = '详情';
  494. checkinInfo.querySelector('.detail').style.display = 'none';
  495. }
  496. };
  497.  
  498. checkinInfo.querySelector('.close').onclick = function() {
  499. if (currentTask) {
  500. currentTask.xhr.abort();
  501. setStatus(`${currentTask.name}中止`);
  502. clearTask();
  503. initCheckinBtn();
  504. } else {
  505. checkinInfo.remove();
  506. checkinCSS.remove();
  507. initCheckinBtn();
  508. }
  509. };
  510.  
  511. [checkinInfo.querySelector('.toDo'), checkinInfo.querySelector('.done')].forEach((ol, i) =>
  512. ['DOMNodeInserted', 'DOMNodeRemoved'].forEach((event) =>
  513. ol.addEventListener(event, function() {
  514. let isRemoval = event != 'DOMNodeInserted',
  515. subtotal = ol.childElementCount - (isRemoval ? 1 : 0);
  516. if (!subtotal)
  517. this.parentNode.style.display = 'none';
  518. else
  519. this.parentNode.removeAttribute('style');
  520. this.previousSibling.innerText = `${i ? '已' : '待'}签${subtotal}个话题`;
  521. Array.from(this.querySelectorAll('li .order')).forEach((el) => /* 计算序号并按小计添加 en quad 进行格式化 */
  522. el.innerText = (Array.from(el.parentNode.parentNode.querySelectorAll('li')).findIndex((li) =>
  523. li === el.parentNode) + (isRemoval ? 0 : 1)).toString().padStart(subtotal.toString().length).replace(/ /g, String.fromCharCode(8192)));
  524. })));
  525.  
  526. /* 开始获取话题列表 */
  527.  
  528. if (lastCheckin.date) {
  529. setStatus(`从${lastCheckin.date}签到记录读取话题列表`);
  530. var lastHuatiList = [],
  531. todayChecked = lastCheckin.date === date;
  532. for (let name in lastCheckin) {
  533. if (!['date', 'nick', 'allChecked'].includes(name)) {
  534. lastHuatiList.push(name);
  535. let hash = lastCheckin[name],
  536. element = initElement(name, hash);
  537. if (!todayChecked) {
  538. checkinInfo.querySelector('.toDo').appendChild(element);
  539. initLog('待签', []);
  540. log.待签.push({name, hash, element});
  541. } else {
  542. checkinInfo.querySelector('.done').appendChild(element);
  543. initLog('已签', {});
  544. log.已签[name] = hash;
  545. }
  546. }
  547. }
  548. if (!todayChecked)
  549. lastCheckin = {};
  550. if (log.hasOwnProperty('待签') && log.待签.length) {
  551. setStatus(`话题列表读取完毕,共${log.待签.length}个话题待签`);
  552. if (config.checkinMode === 'followList') {
  553. if (config.autoCheckin)
  554. checkin(log.待签.shift());
  555. else {
  556. /* 开始签到按钮 */
  557. let startCheckin = document.createElement('a');
  558. startCheckin.classList.add('S_ficon');
  559. startCheckin.onclick = () => checkin(log.待签.shift());
  560. startCheckin.innerText = '[开始签到]';
  561. checkinInfo.querySelector('.status').appendChild(startCheckin);
  562. }
  563. }
  564. } else
  565. initCheckinBtn();
  566. }
  567. switch (config.checkinMode) {
  568. case 'followList':
  569. getFollowList();
  570. break;
  571. case 'whitelist':
  572. getWhitelist();
  573. break;
  574. }
  575. } else
  576. initCheckinBtn();
  577. },
  578.  
  579. importWhitelist = () => Object.keys(lastCheckin).filter((key) => !['date', 'nick', 'allChecked'].includes(key)),
  580.  
  581. checkState = function(list=importWhitelist()) {
  582. if (!arguments.length) {
  583. console.group('话题状态查询');
  584. alterCheckinBtn('查询');
  585. }
  586. let load = (xhr, name, hash) => {
  587. try {
  588. let data = JSON.parse(xhr.responseText),
  589. element = document.getElementById(`_${hash}`);
  590. if (!data.ok) {
  591. list.push(name);
  592. } else {
  593. let cards = data.data.cards;
  594. setStatus((
  595. '我的经验值' != cards[1].card_type_name ? '' : cards[1].card_group.reduce(
  596. (text, card) => 4 != +card.card_type || !/\d/.test(card.desc) ? text : text +
  597. card.desc.replace(/[^\.\d]*(\.?\d+)\D.*/g,
  598. (_, match) => (match.includes('.') ? 'Lv' : '-') + match),
  599. '')), element);
  600. let countsCard = !cards[0].card_group ?
  601. 19 != +cards[0].card_type ? null :
  602. cards[0] : cards[0].card_group.pop();
  603. if (countsCard)
  604. element.title = countsCard.group.map(
  605. (item) => item.item_title + item.item_desc).join() + (!cards[3] || 4 != cards[3].card_type ? '' : ',' + cards[3].desc.replace('超级话题', ''));
  606. if (cards[2].card_group && cards[2].card_group[1].group)
  607. setStatus(';' + cards[2].card_group[1].group.map(
  608. (item) => item.item_desc + item.item_title).join(), element, true);
  609. }
  610. } catch (e) {
  611. console.error(e);
  612. list.push(name);
  613. }
  614. checkState(list);
  615. };
  616. if (!list.length) {
  617. setStatus('查询完毕。');
  618. clearTask();
  619. initCheckinBtn();
  620. console.groupEnd('话题状态查询');
  621. } else {
  622. let name = list.shift(),
  623. hash = lastCheckin[name],
  624. stateCheck = new Task(
  625. `查询${name}话题状态`,
  626. {
  627. method: 'GET',
  628. url: `https://m.weibo.cn/api/container/getIndex?containerid=231140${hash}_-_detail`,
  629. },
  630. (xhr) => load(xhr, name, hash)
  631. );
  632. }
  633. };
  634.  
  635. setupConfig = function() {
  636. const date = getDate();
  637. var configCSS = document.createElement('style');
  638. //configCSS.id = 'configCSS';
  639. configCSS.type = 'text/css';
  640. configCSS.innerHTML = `.checkin.config {z-index:6666;position:fixed;right: 0px;top: 50px;width:540px;opacity: 0.9}.checkin.config a {cursor: pointer}.checkin.config form {height: 288px}.checkin.config header {text-align: center}.checkin.config .close {position: absolute;z-index: 2;left: 12px;top: 2px;font-size: 18px;}.checkin.config header img {position: relative;top: 3px;padding-right: 6px}.checkin.config footer {position: absolute;bottom: 0px;padding: 12px;width: 492px;border-top: solid 1px #ccc}.checkin.config footer input {margin: 0 12px}.checkin.config main {margin: 6px 12px;}.checkin.config fieldset:first-child {width: 240px;float:left;margin-right: 12px}.checkin.config fieldset {padding: 1px 12px}
  641. .checkin.config fieldset > fieldset > legend {text-align: right; padding:3px}.checkin.config input[type=number] {width: 48px}.checkin.config input[type=button] {padding: 0 12px}.checkin.config th {font-weight: bold;padding: 6px 0 3px}.checkin.config table {float: left;margin: 0 6px}.checkin.config div {padding: 6px;height: 160px;overflow-y: scroll;background-color: whitesmoke;line-height: 1.5}${scrollbarStyle('.checkin.config textarea', '.checkin.config div')}.checkin.config span {float: right; margin-top: 3px}
  642. .checkin.config textarea {width: 120px; height: 90px;padding: 6px;margin: 6px 0}`;
  643. document.head.appendChild(configCSS);
  644.  
  645. //var
  646. configForm = document.createElement('div');
  647. //configForm.id = 'configForm';
  648. configForm.className = 'W_layer checkin config';
  649. configForm.innerHTML = `<form class=content><header class=W_layer_title><img src=//img.t.sinajs.cn/t6/style/images/pagecard/icon.png>签到脚本设置<span class=status></span><a title=关闭 class="W_ficon S_ficon close">X</a></header><main><fieldset><legend>参数设定</legend>
  650. <fieldset><legend>签到模式</legend><label class=followList title=先获取话题关注列表再进行签到><input type=radio value=followList name=checkinMode>关注列表模式  <label for=checkNormal><input type=checkbox name=checkNormal for=followList class=sub>普话签到</label></label><br>
  651. <label class=whitelist title=只读取本地名单并按顺序签到><input type=radio value=whitelist name=checkinMode>白名单模式  <input type=button class="edit sub" value=编辑名单></label></fieldset>
  652. <fieldset><legend>运行参数</legend>请求延时 <input type=number name=delay min=0 max=1000 step=100> 毫秒<span><label for=autoCheckin><input type=checkbox name=autoCheckin>自动签到</label><br><label title=自动查询等级、连续签到天数、话题数据及主持人考核进度><input type=checkbox name=autoCheckState>自动查询</label></span><br>请求超时 <input type=number name=timeout min=1000 max=10000 step=100> 毫秒<br>自动重试 <input type=number name=retry min=0 max=10> 次</fieldset>
  653. <fieldset><legend>签到详情</legend>最大高度 <input type=number name=maxHeight min=60 max=1080 step=60> 像素<span><label for=openDetail><input type=checkbox name=openDetail>自动展开</label></span></fieldset>
  654. </fieldset>
  655. <fieldset class=account><legend>账户信息</legend><table><tbody><tr><th>昵称</th></tr><tr><td>${USER.NICK}</td></tr><tr><th>ID</th></tr><tr><td>${USER.UID}</td></tr><tr><th>上次签到</th></tr><tr><td>${lastCheckin.date || '尚无记录'}</td></tr><tr><th><input type=button value=状态查询 class=stateCheck></th></tr><tr><th><input type=button value=清空记录 class=clear ${Object.keys(lastCheckin).length != 0 ? '' : 'disabled'}></th></tr></tbody></table><div>${importWhitelist().map((name) => {
  656. let hash = lastCheckin[name];
  657. return '<p id=_' + hash + '><a href=//weibo.com/p/100808' + hash + ' target=_blank>' + name + '</a><i class=info></i></p>';
  658. }).join('')}</div></fieldset>
  659. <fieldset class="whitelist editor" style=display:none><legend>签到名单编辑</legend>请在下方编辑名单,每行一个话题名,完成后点击[保存名单]按钮。<br><textarea class=box placeholder="每行一个话题名,不带#号,如\n读书\n美食">${whitelist.join('\n')}</textarea><span><input type=button class=save value=保存名单 disabled><input type=button class=import value=导入列表 title=导入签到记录中的话题列表></fieldset>
  660. <footer><input type=button value=保存 class=save disabled><input type=button value=还原 class=restore disabled><input type=button value=重置 class=default><span><a href=//greasyfork.org/scripts/32143/feedback target=_blank>GreasyFork</a> / <a href=//gist.github.com/xyauhideto/b9397058ca3166b87e706cbb7249bd54 target=_blank>Gist</a> / <a href=//weibo.com/678896489 target=_blank>微博</a> 报错请F12提供后台记录</span></footer> </form>`;
  661. document.body.appendChild(configForm);
  662. alterCheckinBtn('设置');
  663.  
  664. let inputs = Array.from(configForm.querySelectorAll('input:not([type=button])')),
  665.  
  666. getWhitelist = () => configForm.querySelector('.checkin .whitelist .box').value.split('\n').filter((name) => name.trim().length),
  667. getInputs = () => inputs.reduce((conf, input) => {
  668. if (!(input.type === 'radio' && !input.checked))
  669. conf[input.name] = input.type != 'number' ? input.type != 'checkbox' ? input.value : input.checked : Math.max(+input.min, Math.min(+input.max, +input.value));
  670. return conf;
  671. }, {}),
  672.  
  673. initForm = function(conf=config) {
  674. for (let [key, value] of Object.entries(conf)) {
  675. let input = typeof value === 'string' ? configForm.querySelector(`[name=${key}][value=${value}]`) : document.querySelector(`[name=${key}]`);
  676. if (typeof value === 'boolean')
  677. input.checked = value;
  678. else if (typeof value === 'string') {
  679. input.checked = true;
  680. input.parentNode.querySelector('.sub').removeAttribute('disabled');
  681. let other = configForm.querySelector(`[name=${key}]:not([value=${value}])`).parentNode.querySelector('.sub');
  682. if (other.value === '退出编辑')
  683. other.click();
  684. other.disabled = true;
  685. } else
  686. input.value = value;
  687. }
  688. configForm.querySelector('.restore').disabled = isEqual(conf, config);
  689. configForm.querySelector('.default').disabled = isEqual(conf, DEFAULT_CONFIG);
  690. configForm.querySelector('footer .save').disabled = configForm.querySelector('.restore').disabled;
  691. configForm.querySelector('.whitelist .box').oninput();
  692. },
  693.  
  694. /**
  695. * 简单对象、阵列比较
  696. * @param {object|array} x 比较对象/阵列x
  697. * @param {object|array} y 比较对象/阵列y
  698. * @return {boolean} 比较结果
  699. */
  700. isEqual = function(x, y) {
  701. if (Object.values(x).length != Object.values(y).length)
  702. return false;
  703. if (x instanceof Array) {
  704. for (let value of x) {
  705. if (!y.includes(value))
  706. return false;
  707. }
  708. } else {
  709. for (let key in x) {
  710. if (!y.hasOwnProperty(key) || x[key] != y[key])
  711. return false;
  712. }
  713. }
  714. return true;
  715. };
  716.  
  717. configForm.querySelector('.stateCheck').onclick = ()=>checkState();
  718.  
  719. configForm.querySelector('footer .save').onclick = function() {
  720. config = getInputs();
  721. if (!configForm.querySelector('.whitelist .save').disabled && confirm('尚未保存签到名单,一起保存?'))
  722. configForm.querySelector('.whitelist .save').click();
  723. if (configForm.querySelector('.whitelist .edit').value === '退出编辑')
  724. configForm.querySelector('.whitelist .edit').click();
  725. GM_setValue(`config${USER.UID}`, JSON.stringify(config));
  726. initForm();
  727. };
  728. configForm.querySelector('.restore').onclick = () => initForm();
  729. configForm.querySelector('.default').onclick = function() {
  730. GM_deleteValue(`config${USER.UID}`);
  731. initForm(DEFAULT_CONFIG);
  732. };
  733. configForm.querySelector('.clear').onclick = function() {
  734. console.warn('清空上次签到');
  735. console.table(lastCheckin);
  736. GM_deleteValue(`lastCheckin${USER.UID}`);
  737. lastCheckin = {};
  738. configForm.querySelector('tr:nth-of-type(6)>td').innerText = '尚无记录';
  739. configForm.querySelector('div').innerText = '';
  740. this.disabled = true;
  741. };
  742. configForm.querySelector('.close').onclick = function() {
  743. if (currentTask) {
  744. currentTask.xhr.abort();
  745. setStatus(`${currentTask.name}中止`);
  746. clearTask();
  747. initCheckinBtn();
  748. } else {
  749. configCSS.remove();
  750. configForm.remove();
  751. initCheckinBtn();
  752. }
  753. };
  754.  
  755. inputs.forEach(function(input) {
  756. input.onchange = () => initForm(getInputs());
  757. if (input.parentNode.title) {
  758. input.onfocus = () => {
  759. let tip = document.createElement('i');
  760. tip.innerText = input.parentNode.title;
  761. tip.style = `position:absolute;left:${input.offsetLeft - 10 * input.parentNode.title.length}px;top:${input.offsetTop + 15}px;padding:3px;border:1px solid grey;color:grey;background-color:white;box-shadow:1px 1px 2px`;
  762. input.parentNode.append(tip);
  763. };
  764. input.onblur = () => input.parentNode.lastChild.remove();
  765. }
  766. });
  767.  
  768. configForm.querySelector('.whitelist .edit').onclick = function() {
  769. if (this.value === '编辑名单') {
  770. configForm.querySelector('.whitelist .box').value = whitelist.join('\n');
  771. configForm.querySelector('.account').style.display = 'none';
  772. configForm.querySelector('.whitelist.editor').removeAttribute('style');
  773. this.value = '退出编辑';
  774. } else {
  775. configForm.querySelector('.whitelist.editor').style.display = 'none';
  776. configForm.querySelector('.account').removeAttribute('style');
  777. this.value = '编辑名单';
  778. }
  779. };
  780. configForm.querySelector('.whitelist .save').onclick = function() {
  781. let whitelist_ = getWhitelist();
  782. if (whitelist_.length || confirm('尚未设定白名单,继续保存?')) {
  783. whitelist = whitelist_;
  784. GM_setValue(`whitelist${USER.UID}`, JSON.stringify(whitelist));
  785. configForm.querySelector('.whitelist.editor').style.display = 'none';
  786. configForm.querySelector('.account').removeAttribute('style');
  787. configForm.querySelector('.whitelist .edit').value = '编辑名单';
  788. configForm.querySelector('.whitelist .box').oninput();
  789. }
  790. };
  791. configForm.querySelector('.checkin .whitelist .import').onclick = function() {
  792. configForm.querySelector('.whitelist .box').value = importWhitelist().join('\n');
  793. configForm.querySelector('.whitelist .box').oninput();
  794. };
  795. configForm.querySelector('.whitelist .box').oninput = function() {
  796. let whitelist_ = getWhitelist();
  797. configForm.querySelector('.whitelist .save').disabled = isEqual(Object.assign({}, whitelist_), Object.assign({}, whitelist));
  798. configForm.querySelector('.whitelist .import').disabled = isEqual(whitelist_, importWhitelist());
  799. };
  800.  
  801. initForm();
  802. },
  803.  
  804. /**
  805. * 提示签到状态
  806. * @param {string|node} status 当前状态
  807. * @param {node} [element=checkinStatus] 显示提示的节点
  808. * @param {boolean} [append=false] 追加节点
  809. */
  810. setStatus = function(status, element=document.querySelector('.checkin .status'), append=false) {
  811. if (element.id && element.id.startsWith('_'))
  812. element = element.querySelector('.info');
  813.  
  814. if (typeof status === 'string' && status)
  815. console.info(status);
  816.  
  817. if (append) {
  818. if (typeof status !== 'string')
  819. element.appendChild(status);
  820. else
  821. element.innerHTML += status;
  822. } else
  823. element.innerHTML = status;
  824. },
  825.  
  826. scrollbarStyle = function() {
  827. return Array.from(arguments).map((elementSelector) => `${elementSelector}::-webkit-scrollbar {width: 4px;background-color: #f2f2f5;border-radius: 2px;}${elementSelector}::-webkit-scrollbar-thumb {width: 4px;background-color: #808080;border-radius: 2px;}`).join('');
  828. },
  829.  
  830. /* 隐藏游戏按钮,替换为超话签到 */
  831. checkinBtn = document.createElement('li');
  832. checkinBtn.id = 'checkinBtn';
  833. checkinBtn.innerHTML = `<a><em class="W_ficon checkin S_ficon">s</em><em class="S_txt1">超话签到</em></a>`;
  834. checkinBtn.addEventListener('contextmenu', e => {
  835. e.preventDefault();
  836. e.stopPropagation();
  837. setupConfig();
  838. });
  839. checkinBtn.addEventListener('click', () => huatiCheckin(false));
  840.  
  841. let navLast = document.querySelector('.gn_nav_list li:last-child');
  842. navLast.parentNode.insertBefore(checkinBtn, navLast);
  843. navLast.parentNode.querySelector('a[nm=game]').parentNode.style.display = 'none';
  844.  
  845. /* 清理旧版数据 */
  846. ['autoSignbox', 'todaySigned'].forEach((key) => GM_deleteValue(key));
  847.  
  848. /* 自动签到 */
  849. if (config.autoCheckin)
  850. huatiCheckin();
  851. } catch (ReferenceError) {
  852. console.error(ReferenceError);
  853. setTimeout(this.onload, 500);
  854. }
  855. });