bilibiliHelper.js 76 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192
  1. /*
  2. 哔哩哔哩每日任务(V1.1)
  3. 更新时间: 2024-04-06
  4. 脚本兼容: QuantumultX, Surge, Loon
  5. 脚本作者: MartinsKing(@ClydeTime)
  6. 软件功能: 登录/观看/分享/投币/直播签到/银瓜子转硬币/大会员积分签到/年度大会员每月B币券+等任务
  7. 注意事项:
  8. 抓取cookie时注意保证账号登录状态;
  9. 账号内须有一定数量的关注数,否则无法完成投币;
  10. 当硬币不足5枚,提示硬币不足,停止投币;
  11. 为保证投币任务成功, 脚本有重试机制(最多重试10次), 以确保任务完成, 前提需要您尽可能多的关注Up主;
  12. 年度大会员每月B币券会在每月1号、15号尝试领取,确保应用正常运行, 以防漏领;
  13. 年度大会员自动充电会在每次领劵之后进行, 默认为自己充电, B币多的用户可自行到boxjs设置,以防误充.
  14. 使用声明: ⚠️此脚本仅供学习与交流,请勿贩卖!⚠️
  15. 脚本参考: Nobyda、Wyatt1026、ABreadTree、chavyleung、SocialSisterYi
  16. ************************
  17. QX, Surge, Loon说明:
  18. ************************
  19. 1.获取cookie
  20. ①后台退出手机B站客户端的情况下, 重新打开APP进入主页
  21. ②通过网址「https://www.bilibili.com」登录,登录后当前网页登录状态失效
  22. 如通知成功获取cookie, 则可以使用此签到脚本.
  23. 脚本将在每天上午7点30执行.
  24. 2.投币设置
  25. 定时任务脚本投币规则为: 随机获取关注列表Up主视频, 默认5视频5硬币, 不点赞.
  26. 用户如需要不投币的版本, 请使用boxjs订阅「https://raw.githubusercontent.com/ClydeTime/BiliBili/main/boxjs/BiliBili.boxjs.json」
  27. 将投币次数置为0, 并保存即可.
  28. /***********************
  29. Surge 脚本配置:
  30. ************************
  31. # B站每日等级任务 「请在模块中添加」
  32. https://raw.githubusercontent.com/ClydeTime/BiliBili/main/modules/BiliBiliDailyBonus.sgmodule
  33. ************************
  34. Loon 远程脚本配置:
  35. ************************
  36. # B站每日等级任务 「请在插件中添加」
  37. https://raw.githubusercontent.com/ClydeTime/BiliBili/main/modules/BiliBiliDailyBonus.plugin
  38. ************************
  39. QuantumultX 远程脚本配置:
  40. ************************
  41. [rewrite local]
  42. # > 哔哩哔哩cookie
  43. ^https?:\/\/app\.bilibili\.com\/x\/resource\/fingerprint\? url script-request-header https://git.jojo21.top/shawenguan/Quantumult-X/raw/master/Scripts/bilibili/bilibiliHelper.js
  44. ^https?:\/\/m.bilibili.com/$ url script-request-header https://git.jojo21.top/shawenguan/Quantumult-X/raw/master/Scripts/bilibili/bilibiliHelper.js
  45. [MITM]
  46. hostname = m.bilibili.com,app.bilibili.com
  47. */
  48. const magicJS = MagicJS(`哔哩哔哩`, "INFO");
  49. const format = (ts, fmt = 'yyyy-MM-dd HH:mm:ss') => {
  50. return magicJS.formatDate(new Date(ts), fmt);
  51. }
  52. const check = key =>
  53. !config.hasOwnProperty(key) ||
  54. !config[key].hasOwnProperty("time") ||
  55. !(config[key]["num"] > 0) ||
  56. format(new Date().toDateString()) > config[key].time
  57. const string2object = cookie => {
  58. let obj = {}
  59. let arr = cookie.split("; ")
  60. arr.forEach(function (val) {
  61. let array = val.split("=")
  62. obj[array[0]] = array[1]
  63. })
  64. return obj
  65. }
  66. const isFlag = exec_times =>
  67. config.user.num === 0 ||
  68. config.watch.num === 0 ||
  69. config.share.num === 0 ||
  70. (config.coins.num < exec_times * 10 && Math.floor(config.user.money) > 5)
  71. const getTimestamp = (d=new Date())=>{
  72. return Math.floor(d.getTime()/1000);
  73. }
  74. const startTime = format();
  75. let cards = [];
  76. let config = {
  77. cookie: {},
  78. cookieStr: "",
  79. key: "",
  80. user: {},
  81. watch: {},
  82. share: {},
  83. coins: {},
  84. score: {}
  85. };
  86. let real_times; //实际需要投币次数
  87. async function Main() {
  88. if (magicJS.isRequest) {
  89. magicJS.logger.info("- 正在获取cookie, 请稍后");
  90. await checkHandleRequest();
  91. } else {
  92. await signBiliBili();
  93. }
  94. magicJS.notification.msg('');
  95. }
  96. async function checkHandleRequest(){
  97. const request = magicJS.request;
  98. let cookieStr = request.headers.cookie || request.headers.Cookie;
  99. if(cookieStr){
  100. config.cookie = magicJS.parseCookies(cookieStr);
  101. const PStoreConfig = magicJS.data.read("bilibili_daily_bonus", {})
  102. if (PStoreConfig.cookie && PStoreConfig.cookie.bili_jct !== config.cookie.bili_jct) {
  103. if (PStoreConfig.Settings) config.Settings = PStoreConfig.Settings // 同步boxjs数据
  104. config.FirstInsert = false;
  105. magicJS.logger.info(magicJS.toStr(config));
  106. await persistentStore(config)
  107. } else if (PStoreConfig.cookie) {
  108. magicJS.logger.info("- cookie未失效,无需更新");
  109. } else {
  110. config.FirstInsert = true;
  111. await persistentStore(config);
  112. }
  113. }
  114. }
  115. async function persistentStore(config){
  116. if (config.cookie.DedeUserID) {
  117. const url = $request.url;
  118. config.key = url.match(/.*access_key=(.*?)&build/)?.[1];
  119. config.cookieStr = `DedeUserID=${config.cookie.DedeUserID}; DedeUserID__ckMd5=${config.cookie.DedeUserID__ckMd5}; SESSDATA=${config.cookie.SESSDATA}; bili_jct=${config.cookie.bili_jct}; sid=${config.cookie.sid}`;
  120. if (!config.key) { //网页方式登录
  121. let auth_code = "0", access_key = "0", login_confirm = false;
  122. auth_code = await getAuthCode();
  123. if (auth_code !== "0"){
  124. login_confirm = await loginConfirm(auth_code)
  125. }
  126. if (login_confirm){
  127. access_key = await getAccessKey(auth_code)
  128. }
  129. if (access_key !== "0") {
  130. config.key = access_key
  131. } else {
  132. magicJS.logger.info("- 获取用户access_key失败!");
  133. magicJS.notification.post(magicJS.scriptName, "🤒获取用户access_key失败!");
  134. }
  135. }
  136. const isFirstInsert = config.FirstInsert;
  137. delete config.FirstInsert;
  138. magicJS.logger.info(magicJS.toStr(config))
  139. const successMessage = magicJS.data.write("bilibili_daily_bonus", magicJS.toStr(config))
  140. ? "🎉cookie存储成功"
  141. : "🤒cookie存储失败"
  142. magicJS.notification.post(magicJS.scriptName, isFirstInsert ? "首次获取cookie" : "检测到cookie已更新", successMessage);
  143. } else {
  144. magicJS.notification.post(magicJS.scriptName, "- 尚未登录, 请登录后重新获取cookie");
  145. }
  146. }
  147. async function signBiliBili() {
  148. config = magicJS.data.read("bilibili_daily_bonus", {});
  149. if (config.cookie && await me()) {
  150. await queryStatus();
  151. let exec_times = config.Settings?.exec; //用户设置投币次数
  152. if (!Boolean(exec_times)) {
  153. exec_times = 5;
  154. real_times = 5 - (Number(config.coins.num) / 10);
  155. } else {
  156. exec_times = Number(exec_times);
  157. real_times = Math.max(0, exec_times - (Number(config.coins.num) / 10));
  158. }
  159. let flag = isFlag(exec_times);
  160. if (flag){
  161. await dynamic();
  162. if (cards.length) {
  163. let item = cards[Math.floor(Math.random() * cards.length)];
  164. let card = magicJS.toObj(item.card);
  165. short_link = encodeURIComponent(card?.short_link_v2.replace(/\\\//g, '/'));
  166. await watch(item.desc.rid, item.desc.bvid, card.cid);
  167. await share(item.desc.rid, card.cid, short_link);
  168. } else {
  169. magicJS.logger.info("- 获取视频失败,请重试或寻求帮助");
  170. }
  171. magicJS.logger.info("3️⃣ 投币任务");
  172. if (typeof config.coins.failures !== 'undefined' && config.coins.failures > 0){
  173. config.coins.failures = 0; //重置投币失败次数
  174. }
  175. if (real_times === 0){
  176. magicJS.logger.info(`- 今日已完成 ${config.coins.time}`);
  177. } else {
  178. for (let i = 0; i < real_times; i ++) {
  179. if (Math.floor(config.user.money) <= 5) {
  180. magicJS.logger.info("- 硬币不足,投币失败");
  181. break;
  182. } else {
  183. await coin();
  184. await magicJS.utils.sleep(300) //减少频繁请求概率
  185. }
  186. }
  187. }
  188. magicJS.logger.info("---- 将尝试额外任务")
  189. } else {
  190. magicJS.logger.info("---- 经验值任务均已完成,将尝试额外任务")
  191. }
  192. await liveSign()
  193. await silver2coin()
  194. await vipScoreSign()
  195. if (config.user.vipStatus === 1) {
  196. await vipExtraEx()
  197. await vipScoreGo()
  198. await vipScoreFan()
  199. await vipScoreMovie()
  200. await vipScoreDress()
  201. await vipWatchAccept()
  202. //B币券每月尝试两次领取
  203. let day = magicJS.utils.formatTime(new Date(), 'dd');
  204. if (day === '1' || day === '15') {
  205. if (config.user.vipType === 2) {
  206. await vipPrivilege(1)
  207. await magicJS.utils.sleep(800) //延迟执行,防止领劵延迟
  208. let charge_mid = config.Settings?.charge_mid || config.user.mid //用户设置充电id
  209. let bp_num = config.Settings?.bp_num || 5 //用户设置充电数量
  210. await Charge(charge_mid, bp_num)//充电
  211. for (let i = 2; i <= 7; i++) await vipPrivilege(i)
  212. } else if (config.user.vipType === 1) {
  213. await vipPrivilege(6)
  214. await vipPrivilege(7)
  215. }
  216. }
  217. }
  218. flag = !isFlag(exec_times)
  219. let title = `登录${config.user.num}/观看${config.watch.num}/分享${config.share.num}/投币${config.coins.num / 10}${flag ? "已完成" : "未完成"}`
  220. magicJS.logger.info(`#### ${title}`)
  221. magicJS.logger.info(`- 登录时间: ${config.user.time || "暂无"}`)
  222. magicJS.logger.info(`- 观看时间: ${config.watch.time || "暂无"}`)
  223. magicJS.logger.info(`- 分享时间: ${config.share.time || "暂无"}`)
  224. magicJS.logger.info(`- 投币时间: ${config.coins.time || "暂无"}`)
  225. notice = {
  226. title: `[${config.user.uname}]`,
  227. subTitle: `${flag ? "✅任务完成" : "❗️有未完成的任务"}`,
  228. content:
  229. `任务:登录(观看)${check("watch") ? "" : "+10exp"} 分享${check("share") ? "" : "+5exp"} 投币${check("coins") ? "" : "+50exp"}\n` +
  230. `经验:当前${config.user.level_info.current_exp}/下级${config.user.level_info.next_exp}/满级28800\n` +
  231. `等级:当前${config.user.level_info.current_level}级 升满级最快需${Math.ceil((config.user.v6_exp)/65)}天`,
  232. }
  233. magicJS.notification.post(notice.title, notice.subTitle, notice.content)
  234. } else {
  235. magicJS.notification.post(`任务失败`,`📅 ${startTime}`, "🤒请更新cookie")
  236. }
  237. }
  238. async function getAuthCode() {
  239. const body = {
  240. appkey: "27eb53fc9058f8c3",
  241. local_id: 0,
  242. ts: getTimestamp()
  243. }
  244. const sortedBody = magicJS.objToQueryStr(Object.fromEntries(new Map(Array.from(Object.entries(body)).sort())))
  245. const sign = md5(sortedBody + 'c2ed53a74eeefe3cf99fbd01d8c9c375')
  246. body['sign'] = sign
  247. const myRequest = {
  248. url: "https://passport.bilibili.com/x/passport-tv-login/qrcode/auth_code",
  249. headers: {
  250. "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
  251. },
  252. body: magicJS.objToQueryStr(body)
  253. }
  254. return await magicJS.http.get(myRequest).then(response => {
  255. try {
  256. const body = response.body;
  257. if (body.code === 0 && body.message === "0") {
  258. magicJS.logger.info("- 获取auth_code成功")
  259. return body.data.auth_code
  260. } else {
  261. magicJS.logger.info("- 获取auth_code失败")
  262. return "0"
  263. }
  264. } catch (e) {
  265. magicJS.logger.error(JSON.stringify(e));
  266. }
  267. })
  268. }
  269. async function loginConfirm(auth_code) {
  270. const body = {
  271. auth_code,
  272. build: 7082000,
  273. csrf: config.cookie.bili_jct
  274. }
  275. const myRequest = {
  276. url: "https://passport.bilibili.com/x/passport-tv-login/h5/qrcode/confirm",
  277. headers: {
  278. "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
  279. 'cookie': `DedeUserID=${config.cookie.DedeUserID}; SESSDATA=${config.cookie.SESSDATA}`
  280. },
  281. body: magicJS.objToQueryStr(body)
  282. }
  283. return await magicJS.http.get(myRequest).then(response => {
  284. try {
  285. const body = response.body;
  286. if (body.code === 0 && body.message === "0") {
  287. magicJS.logger.info("- 确认登录成功")
  288. return true
  289. } else {
  290. magicJS.logger.info("- 确认登录失败")
  291. return false
  292. }
  293. } catch (e) {
  294. magicJS.logger.error(JSON.stringify(e));
  295. }
  296. })
  297. }
  298. async function getAccessKey(auth_code) {
  299. const body = {
  300. appkey: "27eb53fc9058f8c3",
  301. auth_code,
  302. local_id: 0,
  303. ts: getTimestamp()
  304. }
  305. const sortedBody = magicJS.objToQueryStr(Object.fromEntries(new Map(Array.from(Object.entries(body)).sort())))
  306. const sign = md5(sortedBody + 'c2ed53a74eeefe3cf99fbd01d8c9c375')
  307. body['sign'] = sign
  308. const myRequest = {
  309. url: "https://passport.bilibili.com/x/passport-tv-login/qrcode/poll",
  310. headers: {
  311. "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
  312. },
  313. body: magicJS.objToQueryStr(body)
  314. }
  315. return await magicJS.http.get(myRequest).then(response => {
  316. try {
  317. const body = response.body;
  318. if (body.code === 0 && body.message === "0") {
  319. magicJS.logger.info("- 获取access_key成功")
  320. return body.data.access_token
  321. } else {
  322. magicJS.logger.info("- 获取access_key失败")
  323. return "0"
  324. }
  325. } catch (e) {
  326. magicJS.logger.error(JSON.stringify(e));
  327. }
  328. })
  329. }
  330. async function watch(aid, bvid, cid) {
  331. magicJS.logger.info("1️⃣ 观看(登录)任务")
  332. if (check("watch")) {
  333. magicJS.logger.info(`- 正在观看(登录)(${bvid})`)
  334. const body = {
  335. aid,
  336. cid,
  337. bvid,
  338. mid: config.user.mid,
  339. csrf: config.cookie.bili_jct,
  340. played_time : 1,
  341. real_played_time: 1,
  342. realtime: 1,
  343. start_ts: getTimestamp(),
  344. type: 3,
  345. dt: 2,
  346. play_type: 0,
  347. from_spmid: 0,
  348. spmid: 0,
  349. auto_continued_play: 0,
  350. refer_url: "https%3A%2F%2Ft.bilibili.com%2F",
  351. bsource: ""
  352. }
  353. const myRequest = {
  354. url: 'https://api.bilibili.com/x/click-interface/web/heartbeat',
  355. headers: {
  356. "cookie": config.cookieStr,
  357. "referrer": `https://www.bilibili.com/video/${bvid}`
  358. },
  359. body: magicJS.objToQueryStr(body)
  360. }
  361. await magicJS.http.get(myRequest).then(response => {
  362. const body = response.body;
  363. if (body?.code === 0) {
  364. magicJS.logger.info(`- 累计观看(登录)次数 ${(config.watch.num || 0) + 1}`)
  365. config.user.num = (config.user.num || 0) + 1
  366. config.watch.num = (config.watch.num || 0) + 1
  367. magicJS.data.write("bilibili_daily_bonus", magicJS.toStr(config))
  368. } else {
  369. magicJS.logger.info("- 观看失败, 失败原因: " + body?.message)
  370. }
  371. })
  372. } else {
  373. magicJS.logger.info(`- 今日已经观看 ${config.watch.time}`)
  374. }
  375. }
  376. async function share(aid, cid, short_link) {
  377. magicJS.logger.info("2️⃣ 分享任务")
  378. if (check("share")) {
  379. magicJS.logger.info("- 正在分享, aid=" + aid)
  380. const body = {
  381. access_key: config.key.replace(/&actionKey=.*?&appkey=.*$/, ''),
  382. actionKey: 'appkey',
  383. appkey: '27eb53fc9058f8c3',
  384. build: '72700100',
  385. c_locale: 'zh-Hans_CN',
  386. device: 'phone',
  387. disable_rcmd: 0,
  388. link: short_link,
  389. mobi_app: 'iphone',
  390. object_extra_fields: '%7B%7D',
  391. oid: aid,
  392. panel_type: 1,
  393. platform: 'ios',
  394. s_locale:'zh-Hans_CN',
  395. share_channel: 'WEIXIN',
  396. share_id: 'main.ugc-video-detail.0.0.pv',
  397. share_origin: 'vinfo_share',
  398. sid: cid,
  399. spm_id: 'main.ugc-video-detail.0.0',
  400. statistics: '%7B%22appId%22%3A1%2C%22version%22%3A%227.27.0%22%2C%22abtest%22%3A%22%22%2C%22platform%22%3A1%7D',
  401. success: 1,
  402. ts: getTimestamp()
  403. }
  404. const sign = md5(magicJS.objToQueryStr(body) + 'c2ed53a74eeefe3cf99fbd01d8c9c375')
  405. body['sign'] = sign
  406. const myRequest = {
  407. url: 'https://api.bilibili.com/x/share/finish',
  408. headers: {},
  409. body: magicJS.objToQueryStr(Object.fromEntries(new Map(Array.from(Object.entries(body)).sort())))
  410. }
  411. await magicJS.http.get(myRequest).then(response => {
  412. const body = response.body;
  413. if (body?.code === 0) {
  414. config.share.num = (config.share.num || 0) + 1
  415. magicJS.logger.info("- 分享成功")
  416. magicJS.data.write("bilibili_daily_bonus", magicJS.toStr(config))
  417. } else {
  418. magicJS.logger.info("- 分享失败, 失败原因: " + body?.message)
  419. }
  420. })
  421. } else {
  422. magicJS.logger.info(`- 今日已经分享 ${config.share.time}`)
  423. }
  424. }
  425. async function coin() {
  426. if (config.coins.num >= 50) {
  427. magicJS.logger.info(`- 今日已完成 ${config.coins.time}`)
  428. return
  429. }
  430. let like_uid_list = await getFavUid()
  431. if (like_uid_list && like_uid_list.length > 0) {
  432. let aid = await getFavAid(like_uid_list)
  433. //magicJS.logger.info("即将投币的视频aid: " + aid)
  434. if (aid !== 0) {
  435. const body = {
  436. aid,
  437. multiply: 1,
  438. select_like: 0,
  439. cross_domain: true,
  440. csrf: config.cookie.bili_jct
  441. }
  442. const myRequest = {
  443. url: "https://api.bilibili.com/x/web-interface/coin/add",
  444. headers: {
  445. 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36',
  446. 'accept': 'application/json, text/plain, */*',
  447. 'content-type': 'application/x-www-form-urlencoded',
  448. 'origin': 'https://www.bilibili.com',
  449. 'referer': 'https://www.bilibili.com/video/BV1MT411G7fG?vd_source=1970993e2eff4af7be029aefcfa468b8',
  450. 'cookie': config.cookieStr + ';buvid3=fuckchenruilovelaoliu'
  451. },
  452. body: magicJS.objToQueryStr(body)
  453. }
  454. await magicJS.http.get(myRequest).then(async response => {
  455. try {
  456. const body = response.body;
  457. if (body?.code === 0 && body?.message === "0") {
  458. magicJS.logger.info("- 投币成功")
  459. config.user.money -= 1
  460. config.coins.num += 10
  461. magicJS.data.write("bilibili_daily_bonus", magicJS.toStr(config))
  462. } else {
  463. magicJS.logger.info("- 投币失败,失败原因 " + body.message)
  464. config.coins.failures = (config.coins.failures === 0 || typeof config.coins.failures === 'undefined' ? 1 : config.coins.failures + 1)
  465. magicJS.data.write("bilibili_daily_bonus", magicJS.toStr(config))
  466. if (config.coins.failures < 11) {
  467. magicJS.logger.info("- 正在重试...重试次数 " + (config.coins.failures - 1) + "(超过十次不再重试)")
  468. await coin()
  469. }
  470. }
  471. } catch (e) {
  472. magicJS.logger.error(JSON.stringify(e));
  473. }
  474. })
  475. } else {
  476. magicJS.logger.info("获取随机投币视频失败")
  477. }
  478. } else {
  479. magicJS.logger.info("获取随机关注用户列表失败")
  480. }
  481. }
  482. async function getFavUid() {
  483. const myRequest = {
  484. url: `https://api.bilibili.com/x/relation/followings?vmid=${config.cookie.DedeUserID}&ps=10&order_type=attention`,
  485. headers: {
  486. 'cookie': config.cookieStr
  487. }
  488. }
  489. return await magicJS.http.get(myRequest).then(response => {
  490. try {
  491. const body = response.body;
  492. let like_uid_list = new Array()
  493. if (body?.code === 0) {
  494. magicJS.logger.info("- 获取关注列表成功")
  495. let like_list = body?.data?.list
  496. for (let i = 0; i < like_list.length; i ++) {
  497. like_uid_list[i] = like_list[i].mid
  498. }
  499. return like_uid_list
  500. } else {
  501. magicJS.logger.info("- 获取关注列表成失败")
  502. magicJS.logger.info("- 失败原因 " + body?.message)
  503. return like_uid_list
  504. }
  505. } catch (e) {
  506. magicJS.logger.error(JSON.stringify(e));
  507. }
  508. })
  509. }
  510. async function getFavAid(arr) {
  511. //magicJS.logger.info("- 获取关注列表中的随机视频")
  512. let random_int = Math.floor((Math.random()*arr.length))
  513. let random_mid = arr[random_int]
  514. let wbiSigns = getWbiSigns({mid: random_mid})
  515. const myRequest = {
  516. url: `https://api.bilibili.com/x/space/wbi/arc/search?${wbiSigns}`,
  517. headers: {
  518. 'cookie': config.cookieStr
  519. }
  520. }
  521. return await magicJS.http.get(myRequest).then(response => {
  522. try {
  523. const body = response.body;
  524. if (body?.code === 0) {
  525. magicJS.logger.info("- 获取投币视频成功")
  526. let vlist = body.data?.list?.vlist
  527. let random_v_int = Math.floor((Math.random() * vlist.length))
  528. let aid = vlist[random_v_int]?.aid
  529. magicJS.logger.info("- 作者: " + vlist[random_v_int]['author'] + "; 视频标题: " + vlist[random_v_int]['title'])
  530. return aid
  531. } else {
  532. magicJS.logger.info("- 获取投币视频失败")
  533. magicJS.logger.info("- 失败原因 " + body?.message)
  534. return 0
  535. }
  536. } catch (e) {
  537. magicJS.logger.error(JSON.stringify(e));
  538. }
  539. }, reason => {
  540. magicJS.logger.info("- 获取投币视频失败")
  541. magicJS.logger.info("- 失败原因 " + magicJS.toStr(reason))
  542. return 0
  543. })
  544. }
  545. async function silver2coin() {
  546. magicJS.logger.info("#### 银瓜子兑换硬币任务")
  547. const body = {
  548. csrf: config.cookie.bili_jct,
  549. csrf_token: config.cookie.bili_jct
  550. }
  551. const myRequest = {
  552. url: "https://api.live.bilibili.com/xlive/revenue/v1/wallet/silver2coin",
  553. headers: {
  554. 'cookie': config.cookieStr
  555. },
  556. body: magicJS.objToQueryStr(body)
  557. }
  558. await magicJS.http.get(myRequest).then(response => {
  559. try {
  560. let result = response.body;
  561. let title = `银瓜子转硬币`;
  562. // 兑换成功
  563. if (result && result.code === 0) {
  564. let subTitle = `- ${result.message}`
  565. let detail = `- 成功兑换: ${result.data.coin} 个硬币\n当前银瓜子: ${result.data.silver} , 当前金瓜子: ${result.data.gold}`
  566. magicJS.logger.info(subTitle)
  567. magicJS.logger.info(detail)
  568. magicJS.notification.post(title, subTitle, detail)
  569. }
  570. // 兑换中止(重复兑换&银瓜子不足)
  571. else if (result && result.code === 403) {
  572. let subTitle = "- 未成功兑换"
  573. let detail = `- 原因: ${result.message}`
  574. magicJS.logger.info(subTitle)
  575. magicJS.logger.info(detail)
  576. magicJS.notification.post(title, subTitle, detail)
  577. }
  578. // 兑换失败
  579. else {
  580. let subTitle = "- 兑换失败"
  581. let detail = `- 原因: ${result.message}`
  582. magicJS.logger.info(subTitle)
  583. magicJS.logger.info(detail)
  584. magicJS.notification.post(title, subTitle, detail)
  585. }
  586. } catch (e) {
  587. magicJS.logger.error(JSON.stringify(e));
  588. }
  589. }).catch(err => {
  590. const msg = `兑换异常\n${JSON.stringify(err)}`;
  591. magicJS.logger.error(msg);
  592. reject(msg);
  593. });
  594. }
  595. async function liveSign() {
  596. magicJS.logger.info("#### 直播签到任务")
  597. const myRequest = {
  598. url: "https://api.live.bilibili.com/xlive/web-ucenter/v1/sign/DoSign",
  599. headers: {
  600. 'cookie': config.cookieStr
  601. }
  602. }
  603. await magicJS.http.get(myRequest).then(response => {
  604. try {
  605. let body = response.body;
  606. if (body?.code === 0) {
  607. magicJS.logger.info("- 签到成功")
  608. magicJS.logger.info(`签到奖励:${body.data.text},连续签到${body.data.hadSignDays}天`)
  609. } else if (body && body.code === 1011040){
  610. magicJS.logger.info("- 今日已完成")
  611. } else {
  612. magicJS.logger.info("- 签到失败")
  613. magicJS.logger.info("- 失败原因 " + body?.message)
  614. }
  615. } catch (e) {
  616. magicJS.logger.error(JSON.stringify(e));
  617. }
  618. })
  619. }
  620. async function vipScoreSign() {
  621. magicJS.logger.info("#### 大会员大积分签到任务")
  622. if (config.user.vipStatus === 0) {
  623. magicJS.logger.info("- 当前用户非大会员, 无法完成任务")
  624. } else {
  625. if (check("score")) {
  626. const myRequest = {
  627. url: "https://api.bilibili.com/pgc/activity/score/task/sign",
  628. method: "POST",
  629. headers: {
  630. 'Referer': 'https://big.bilibili.com/mobile/bigPoint/task',
  631. 'cookie': config.cookieStr
  632. }
  633. }
  634. await magicJS.http.get(myRequest).then(response => {
  635. try {
  636. const body = response.body;
  637. if (body?.code === 0 && body?.message === "success") {
  638. magicJS.logger.info("- 签到成功")
  639. config.score.time = startTime
  640. config.score.num = 1
  641. magicJS.data.write("bilibili_daily_bonus", magicJS.toStr(config))
  642. } else {
  643. magicJS.logger.info("- 签到失败")
  644. magicJS.logger.info("- 失败原因 " + body?.message)
  645. }
  646. } catch (e) {
  647. magicJS.logger.error(JSON.stringify(e));
  648. }
  649. })
  650. } else {
  651. magicJS.logger.info("- 今日已完成")
  652. }
  653. }
  654. }
  655. async function vipExtraEx() {
  656. magicJS.logger.info("#### 大会员每日额外经验值")
  657. const body = {
  658. csrf: config.cookie.bili_jct,
  659. ts: getTimestamp(),
  660. buvid: config.cookie.Buvid,
  661. mobi_app: 'iphone',
  662. platform: 'ios',
  663. appkey: '27eb53fc9058f8c3',
  664. access_key: config.key
  665. }
  666. const sortedBody = magicJS.objToQueryStr(Object.fromEntries(new Map(Array.from(Object.entries(body)).sort())))
  667. const sign = md5(sortedBody + 'c2ed53a74eeefe3cf99fbd01d8c9c375')
  668. body['sign'] = sign
  669. const myRequest = {
  670. url: "https://api.bilibili.com/x/vip/experience/add",
  671. headers: {
  672. 'accept': 'application/json, text/plain, */*',
  673. 'app-key': 'iphone'
  674. },
  675. body: magicJS.objToQueryStr(body)
  676. }
  677. await magicJS.http.get(myRequest).then(response => {
  678. try {
  679. const body = response.body;
  680. if (body?.code === 0 && body?.message === "0") {
  681. magicJS.logger.info("- 成功获得10经验值")
  682. } else {
  683. magicJS.logger.info("- 每日额外经验任务失败")
  684. magicJS.logger.info("- 失败原因 " + body?.message)
  685. }
  686. } catch (e) {
  687. magicJS.logger.error(JSON.stringify(e));
  688. }
  689. })
  690. }
  691. async function vipScoreGo() {
  692. magicJS.logger.info("#### 大会员浏览会员购10s任务")
  693. const myRequest = {
  694. url: "https://show.bilibili.com/api/activity/fire/common/event/dispatch",
  695. headers: {
  696. 'Content-Type' : 'application/json',
  697. 'Cookie': config.cookieStr
  698. },
  699. body: `{"eventId":"hevent_oy4b7h3epeb"}`
  700. }
  701. await magicJS.http.get(myRequest).then(response => {
  702. try {
  703. const body = response.body;
  704. if (body?.code === 0 && body?.message === "SUCCESS") {
  705. magicJS.logger.info("- 成功获得10点大积分")
  706. } else {
  707. magicJS.logger.info("- 浏览会员购任务失败")
  708. magicJS.logger.info("- 失败原因 " + body?.message)
  709. }
  710. } catch (e) {
  711. magicJS.logger.error(JSON.stringify(e));
  712. }
  713. })
  714. }
  715. async function vipScoreFan() {
  716. magicJS.logger.info("#### 大会员浏览追番频道10s任务")
  717. const myRequest = {
  718. url: `https://api.bilibili.com/pgc/activity/deliver/task/complete?access_key=${config.key}&position=jp_channel&sign=768d600feba34e6d1109e4157c0f0c5f&task_sign=557D1ACE13E9E81393259FFB621D6D0E`,
  719. method: "POST",
  720. headers: {}
  721. }
  722. await magicJS.http.get(myRequest).then(response => {
  723. try {
  724. const body = response.body;
  725. if (body?.code === 0 && body?.message === "success") {
  726. magicJS.logger.info("- 成功获得10点大积分")
  727. } else {
  728. magicJS.logger.info("- 浏览追番频道任务失败")
  729. magicJS.logger.info("- 失败原因 " + body?.message)
  730. }
  731. } catch (e) {
  732. magicJS.logger.error(JSON.stringify(e));
  733. }
  734. })
  735. }
  736. async function vipScoreMovie() {
  737. magicJS.logger.info("#### 大会员浏览影视频道10s任务")
  738. const myRequest = {
  739. url: `https://api.bilibili.com/pgc/activity/deliver/task/complete?access_key=${config.key}&position=tv_channel&sign=09ece1c295cb86d74778b93c59c0da3a&task_sign=B7DA5FAE25C39F53C62C03076CF2878B`,
  740. method: "POST",
  741. headers: {}
  742. }
  743. await magicJS.http.get(myRequest).then(response => {
  744. try {
  745. const body = response.body;
  746. if (body?.code === 0 && body?.message === "success") {
  747. magicJS.logger.info("- 成功获得10点大积分")
  748. } else {
  749. magicJS.logger.info("- 浏览影视频道任务失败")
  750. magicJS.logger.info("- 失败原因 " + body?.message)
  751. }
  752. } catch (e) {
  753. magicJS.logger.error(JSON.stringify(e));
  754. }
  755. })
  756. }
  757. async function vipScoreDress() {
  758. magicJS.logger.info("#### 大会员浏览装扮商城主页任务")
  759. const body = {
  760. csrf: config.cookie.bili_jct,
  761. ts: getTimestamp(),
  762. taskCode: 'dress-view',
  763. access_key: config.key
  764. }
  765. const myRequest = {
  766. url: 'https://api.bilibili.com/pgc/activity/score/task/complete/v2',
  767. headers: {},
  768. body: magicJS.objToQueryStr(body)
  769. }
  770. await magicJS.http.get(myRequest).then(response => {
  771. try {
  772. const body = response.body;
  773. if (body?.code === 0 && body?.message === "success") {
  774. magicJS.logger.info("- 成功获得10点大积分")
  775. } else {
  776. magicJS.logger.info("- 浏览装扮商城主页任务失败")
  777. }
  778. } catch (e) {
  779. magicJS.logger.error(JSON.stringify(e));
  780. }
  781. })
  782. }
  783. async function vipWatchAccept() {
  784. magicJS.logger.info("#### 接取大会员观看剧集10min任务")
  785. const body = {
  786. csrf: config.cookie.bili_jct,
  787. ts: getTimestamp(),
  788. taskCode: 'ogvwatchnew',
  789. mobi_app: 'iphone',
  790. platform: 'ios',
  791. appkey: '27eb53fc9058f8c3',
  792. access_key: config.key
  793. }
  794. const sortedBody = magicJS.objToQueryStr(Object.fromEntries(new Map(Array.from(Object.entries(body)).sort())))
  795. const sign = md5(sortedBody + 'c2ed53a74eeefe3cf99fbd01d8c9c375')
  796. body['sign'] = sign
  797. const myRequest = {
  798. url: 'https://api.bilibili.com/pgc/activity/score/task/receive/v2',
  799. headers: {
  800. 'Content-Type': 'application/x-www-form-urlencoded',
  801. 'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 16_6_1 like Mac OS X) AppleWebKit/615.2.9.10.4 (KHTML, like Gecko) Mobile/20F75 BiliApp/77200100 os/ios model/iPhone 15 Pro Max mobi_app/iphone build/77200100 osVer/17.4.1 network/2 channel/AppStore c_locale/zh-Hans_CN s_locale/zh-Hans_CN disable_rcmd/0',
  802. 'Cookie': `SESSDATA=${config.cookie.SESSDATA}`,
  803. 'Referer': `https://big.bilibili.com/mobile/bigPoint/task`
  804. },
  805. body: magicJS.objToQueryStr(body)
  806. }
  807. await magicJS.http.get(myRequest).then(response => {
  808. try {
  809. const body = response.body;
  810. if (body?.code === 0 && body?.message === "success") {
  811. magicJS.logger.info("- 大会员观看剧集任务接取成功, 需自行观看")
  812. } else {
  813. magicJS.logger.info("- 大会员观看剧集任务接取失败")
  814. magicJS.logger.info("- 失败原因 " + body?.message)
  815. }
  816. } catch (e) {
  817. magicJS.logger.error(JSON.stringify(e));
  818. }
  819. })
  820. }
  821. async function vipPrivilege(type) {
  822. magicJS.logger.info("#### 领取大会员月度福利")
  823. const body = {
  824. csrf: config.cookie.bili_jct,
  825. type
  826. }
  827. const myRequest = {
  828. url: 'https://api.bilibili.com/x/vip/privilege/receive',
  829. headers: {
  830. 'Cookie': config.cookieStr
  831. },
  832. body: magicJS.objToQueryStr(body)
  833. }
  834. await magicJS.http.get(myRequest).then(response => {
  835. try {
  836. const body = response.body;
  837. if (body?.code === 0) {
  838. switch (type) {
  839. case 1:
  840. magicJS.logger.info("- 领取年度大会员每月B币券成功")
  841. magicJS.notification.post("年度大会员月度福利", "B币券", "🎉🎉🎉领取成功")
  842. break
  843. case 2:
  844. magicJS.logger.info("- 领取年度大会员每月会员购优惠券成功")
  845. break
  846. case 3:
  847. magicJS.logger.info("- 领取年度大会员每月漫画福利券成功")
  848. break
  849. case 4:
  850. magicJS.logger.info("- 领取年度大会员每月会员购包邮券成功")
  851. break
  852. case 5:
  853. magicJS.logger.info("- 领取年度大会员每月漫画商城优惠券成功")
  854. break
  855. case 6:
  856. magicJS.logger.info("- 领取大会员每月装扮体验卡成功")
  857. break
  858. case 7:
  859. magicJS.logger.info("- 领取大会员每月课堂优惠券成功")
  860. break
  861. default:
  862. break
  863. }
  864. } else {
  865. magicJS.logger.info("- 领取大会员每月福利失败, 福利编码为" + type)
  866. magicJS.logger.info("- 失败原因 " + body?.message)
  867. if (type === 1) {
  868. magicJS.notification.post("年度大会员月度福利", "B币券领取失败", "失败原因为: " + body?.message)
  869. }
  870. //其他福利没什么用,失败也无需单独通知
  871. }
  872. } catch (e) {
  873. magicJS.logger.error(JSON.stringify(e));
  874. }
  875. })
  876. }
  877. async function Charge(mid, bp_num) {
  878. magicJS.logger.info("#### B币券自动充电")
  879. const body = {
  880. bp_num,
  881. is_bp_remains_prior: true,
  882. up_mid: mid,
  883. otype: 'up',
  884. oid: mid,
  885. csrf: config.cookie.bili_jct
  886. }
  887. const myRequest = {
  888. url: 'https://api.bilibili.com/x/ugcpay/web/v2/trade/elec/pay/quick',
  889. headers: {
  890. 'Cookie': config.cookieStr
  891. },
  892. body: magicJS.objToQueryStr(body)
  893. }
  894. await magicJS.http.get(myRequest).then(response => {
  895. try {
  896. const body = response.body;
  897. if (body?.code === 0) {
  898. if (body?.data?.status === 4) {
  899. if (mid === config.user.mid) {
  900. magicJS.logger.info("- 为自己充电成功")
  901. } else {
  902. magicJS.logger.info(`- 为用户id为${mid}的用户充电成功`)
  903. }
  904. } else if (body?.data?.status === -4) {
  905. magicJS.logger.info("- 充电失败, B币不足")
  906. } else {
  907. magicJS.logger.info("- 充电失败")
  908. magicJS.logger.info("- 失败原因 " + body?.message)
  909. }
  910. } else {
  911. magicJS.logger.info("- 充电失败")
  912. magicJS.logger.info("- 失败原因 " + body?.message)
  913. }
  914. } catch (e) {
  915. magicJS.logger.error(JSON.stringify(e));
  916. }
  917. })
  918. }
  919. async function me() {
  920. magicJS.logger.info("#### 用户信息")
  921. const myRequest = {
  922. url: 'https://api.bilibili.com/x/web-interface/nav',
  923. headers: {
  924. "cookie": config.cookieStr
  925. }
  926. }
  927. return await magicJS.http.get(myRequest).then(response => {
  928. try {
  929. const body = response.body;
  930. if (body?.code) {
  931. magicJS.logger.info("- ❌❌获得用户信息失败(请更新cookie)")
  932. magicJS.data.write("bilibili_daily_bonus", null)
  933. return false
  934. } else {
  935. magicJS.logger.info("- 🎉cookie有效任务即将开始🎉")
  936. config.user = body?.data
  937. config.user.num = check("user") ? 1 : (config.user.num || 0) + 1
  938. magicJS.data.write("bilibili_daily_bonus", magicJS.toStr(config))
  939. config.user.mext_exp = config.user.level_info.next_exp - config.user.level_info.current_exp
  940. config.user.next_day = Math.ceil(config.user.mext_exp / 15)
  941. config.user.v6_exp = 28800 - config.user.level_info.current_exp
  942. config.user.v6_day = Math.ceil(config.user.v6_exp / 15)
  943. if (config.user.vipStatus === 1) {
  944. magicJS.logger.info("- 💖尊贵的大会员用户💖")
  945. }
  946. magicJS.logger.info("- 用户名称: " + config.user.uname)
  947. magicJS.logger.info("- 用户ID: " + config.user.mid)
  948. magicJS.logger.info("- 用户硬币: " + Math.floor(config.user.money))
  949. magicJS.logger.info("- 用户B币: " + config.user.wallet.bcoin_balance)
  950. magicJS.logger.info("- 用户等级: " + config.user.level_info.current_level)
  951. magicJS.logger.info(
  952. `- 当前经验: ${config.user.level_info.current_exp}/${config.user.level_info.next_exp}`
  953. )
  954. magicJS.logger.info(`- 升级还需经验: ${config.user.mext_exp}`)
  955. magicJS.logger.info(
  956. `- 距离下级还需: ${config.user.next_day}天(登录 观看 分享)`
  957. )
  958. magicJS.logger.info(
  959. `- 距离满级还需: ${Math.max(0, config.user.v6_day)}天(登录 观看 分享)`
  960. )
  961. magicJS.logger.info(`- 剩余硬币最多可投: ${Math.floor((config.user.money)/5)}天`)
  962. magicJS.logger.info(
  963. "- 距离满级最快还需: " +
  964. Math.max(0, Math.ceil(config.user.v6_exp / 65)) +
  965. "天(日常 + 投币*5)"
  966. )
  967. return true
  968. }
  969. } catch (e) {
  970. magicJS.logger.error(JSON.stringify(e));
  971. }
  972. }, reason => {
  973. magicJS.notification.post(magicJS.scriptName, "- 获取用户信息失败", magicJS.toStr(reason))
  974. return false
  975. })
  976. }
  977. async function queryStatus() {
  978. magicJS.logger.info("#### 检查任务进行状况")
  979. const myRequest = {
  980. url: "https://api.bilibili.com/x/member/web/exp/reward",
  981. headers: {
  982. "cookie": config.cookieStr
  983. }
  984. }
  985. await magicJS.http.get(myRequest).then(response => {
  986. try {
  987. const body = response.body;
  988. if (body?.code === 0) {
  989. if (body.data.login) {
  990. magicJS.logger.info("- 今日已登录")
  991. config.user.num = (config.user.num === 0 ? 1 : config.user.num)
  992. if (!config['user'].hasOwnProperty("time")) {
  993. config.user.time = startTime
  994. }
  995. } else {
  996. magicJS.logger.info("! 今日尚未登录")
  997. config.user.num = 0
  998. }
  999. if (body.data.watch){
  1000. magicJS.logger.info("- 今日已观看")
  1001. config.watch.num = (config.watch.num === 0 || typeof config.watch.num === 'undefined' ? 1 : config.watch.num)
  1002. if (!config['watch'].hasOwnProperty("time")) {
  1003. config.watch.time = startTime
  1004. }
  1005. } else {
  1006. magicJS.logger.info("! 今日尚未观看")
  1007. config.watch.num = 0
  1008. }
  1009. if (body.data.share){
  1010. magicJS.logger.info("- 今日已分享")
  1011. config.share.num = (config.share.num === 0 || typeof config.share.num === 'undefined' ? 1 : config.share.num)
  1012. if (!config['share'].hasOwnProperty("time")) {
  1013. config.share.time = startTime
  1014. }
  1015. } else {
  1016. magicJS.logger.info("! 今日尚未分享")
  1017. config.share.num = 0
  1018. }
  1019. if (body.data.coins === 50){
  1020. magicJS.logger.info("- 今日已投币")
  1021. if (!config['coins'].hasOwnProperty("time")) {
  1022. config.coins.time = startTime
  1023. } else {
  1024. if (format(new Date().toDateString()) > config.coins.time) {
  1025. config.coins.time = startTime
  1026. }
  1027. }
  1028. } else if ((body.data.coins / 10) >= real_times) {
  1029. config.coins.time = startTime
  1030. magicJS.logger.info("- 已完成用户设置的投币量")
  1031. } else if (config.user.money <= 5) {
  1032. magicJS.logger.info("! 硬币数不足")
  1033. } else {
  1034. magicJS.logger.info("! 今日投币未完成")
  1035. }
  1036. config.coins.num = body.data.coins
  1037. magicJS.data.write("bilibili_daily_bonus", magicJS.toStr(config))
  1038. } else {
  1039. magicJS.logger.info("- 查询失败")
  1040. magicJS.logger.info("- 失败原因 " + body?.message)
  1041. }
  1042. } catch (e) {
  1043. magicJS.logger.error(JSON.stringify(e));
  1044. }
  1045. })
  1046. }
  1047. async function dynamic() {
  1048. magicJS.logger.info("#### 获取首页视频")
  1049. const myRequest = {
  1050. url: `https://api.vc.bilibili.com/dynamic_svr/v1/dynamic_svr/dynamic_new?uid=${config.cookie.DedeUserID}&type_list=8&from=&platform=web`,
  1051. headers: {
  1052. "cookie": config.cookieStr
  1053. }
  1054. }
  1055. await magicJS.http.get(myRequest).then(response => {
  1056. try {
  1057. const body = response.body;
  1058. if (body?.data?.cards) {
  1059. cards = body.data.cards
  1060. const { user, watch, share } = config
  1061. user.time = watch.time = share.time = startTime
  1062. magicJS.logger.info("- 获取视频动态成功")
  1063. } else {
  1064. magicJS.logger.info("- 获取视频动态失败")
  1065. }
  1066. } catch (e) {
  1067. magicJS.logger.error(JSON.stringify(e));
  1068. }
  1069. })
  1070. }
  1071. Main()
  1072. .catch((e) => magicJS.logger.error(JSON.stringify(e)))
  1073. .finally(() => magicJS.done());
  1074. // Wbi签名获取
  1075. function getWbiSigns(requestParams) {
  1076. // 从给定字符串生成特定的签名
  1077. function generateSignature(baseString) {
  1078. let signature = "";
  1079. signatureIndices.forEach(index => {
  1080. signature += baseString[index];
  1081. });
  1082. return signature.slice(0, 32);
  1083. }
  1084. // 主要函数来构建请求参数并生成最终的请求字符串
  1085. function buildRequestWithSignature(params, imageKey, subscriptionKey) {
  1086. const signatureBase = generateSignature(imageKey + subscriptionKey);
  1087. const startTimeInMillisecond = new Date().getTime();
  1088. const startTimeInSeconds = parseInt(startTimeInMillisecond / 1000);
  1089. let queryString = "";
  1090. // 添加时间戳到请求参数
  1091. params = Object.assign(params, {
  1092. wts: startTimeInSeconds
  1093. });
  1094. // 将参数对象转换为排序后的查询字符串
  1095. queryString = objectToQueryString(sortedObjectEntries(params));
  1096. // 生成请求ID并附加到查询字符串
  1097. const requestId = md5(queryString + signatureBase);
  1098. return queryString + "&w_rid=" + requestId;
  1099. }
  1100. // 转换对象为查询字符串
  1101. function objectToQueryString(obj) {
  1102. return magicJS.objToQueryStr(Object.fromEntries(new Map(Array.from(Object.entries(obj)).sort())));
  1103. }
  1104. // 获取图片和订阅的关键信息
  1105. function getImageAndSubscriptionKeys() {
  1106. const imageUrl = config.user.wbi_img.img_url;
  1107. const subscriptionUrl = config.user.wbi_img.sub_url;
  1108. return {
  1109. img_key: imageUrl.substring(imageUrl.lastIndexOf("/") + 1).split(".")[0],
  1110. sub_key: subscriptionUrl.substring(subscriptionUrl.lastIndexOf("/") + 1).split(".")[0]
  1111. };
  1112. }
  1113. // 签名索引数组
  1114. const signatureIndices = [
  1115. 46, 47, 18, 2, 53, 8, 23, 32, 15, 50, 10, 31, 58, 3, 45, 35, 27, 43, 5, 49, 33, 9, 42, 19, 29, 28, 14, 39,
  1116. 12, 38, 41, 13, 37, 48, 7, 16, 24, 55, 40, 61, 26, 17, 0, 1, 60, 51, 30, 4, 22, 25, 54, 21, 56, 59, 6, 63,
  1117. 57, 62, 11, 36, 20, 34, 44, 52
  1118. ];
  1119. // 提取图片和订阅关键信息
  1120. const { img_key, sub_key } = getImageAndSubscriptionKeys();
  1121. // 构建并返回请求字符串,包含签名
  1122. return buildRequestWithSignature(requestParams, img_key, sub_key);
  1123. }
  1124. //---SyncByPyScript---MagicJS3-start
  1125. function MagicJS(e="MagicJS",t="INFO"){const r=()=>{const e="undefined"!=typeof $loon,t="undefined"!=typeof $task,n="undefined"!=typeof module,r="undefined"!=typeof $httpClient&&!e,o="undefined"!=typeof $storm,i="undefined"!=typeof $environment&&void 0!==$environment["stash-build"];var s=r||e||o||i;const a="undefined"!=typeof importModule;return{isLoon:e,isQuanX:t,isNode:n,isSurge:r,isStorm:o,isStash:i,isSurgeLike:s,isScriptable:a,get name(){return e?"Loon":t?"QuantumultX":n?"NodeJS":r?"Surge":a?"Scriptable":"unknown"},get build(){return r?$environment["surge-build"]:i?$environment["stash-build"]:o?$storm.buildVersion:void 0},get language(){if(r||i)return $environment.language},get version(){return r?$environment["surge-version"]:i?$environment["stash-version"]:o?$storm.appVersion:n?process.version:void 0},get system(){return r?$environment.system:n?process.platform:void 0},get systemVersion(){if(o)return $storm.systemVersion},get deviceName(){if(o)return $storm.deviceName}}},o=(n,e="INFO")=>{let r=e,t="\n";const o={SNIFFER:6,DEBUG:5,INFO:4,NOTIFY:3,WARNING:2,ERROR:1,CRITICAL:0,NONE:-1},i={SNIFFER:"",DEBUG:"",INFO:"",NOTIFY:"",WARNING:"❗ ",ERROR:"❌ ",CRITICAL:"❌ ",NONE:""},s=(e,t="INFO")=>{o[r]<o[t.toUpperCase()]||console.log(`██[${n}][${t}]`+i[t.toUpperCase()]+e+"\n")};return{getLevel:()=>r,setLevel:e=>{r=e},sniffer:(...e)=>{e=e.join(t);s(e,"SNIFFER")},log:(...e)=>{e=e.join(t);console.log(`██[${n}]`+e+"\n")},debug:(...e)=>{e=e.join(t);s(e,"DEBUG")},info:(...e)=>{e=e.join(t);s(e,"INFO")},notify:(...e)=>{e=e.join(t);s(e,"NOTIFY")},warning:(...e)=>{e=e.join(t);s(e,"WARNING")},error:(...e)=>{e=e.join(t);s(e,"ERROR")},retry:(...e)=>{e=e.join(t);s(e,"RETRY")}}};return new class{constructor(e,t){var n;this._startTime=Date.now(),this.version="3.0.0",this.scriptName=e,this.env=r(),this.logger=o(e,t),this.http="function"==typeof MagicHttp?MagicHttp(this.env,this.logger):void 0,this.data="function"==typeof MagicData?MagicData(this.env,this.logger):void 0,this.notification="function"==typeof MagicNotification?MagicNotification(this.scriptName,this.env,this.logger,this.http):void 0,this.utils="function"==typeof MagicUtils?MagicUtils(this.env,this.logger):void 0,this.qinglong="function"==typeof MagicQingLong?MagicQingLong(this.env,this.data,this.logger):void 0,void 0!==this.data&&(t=this.data.read("magic_loglevel"),n=this.data.read("magic_bark_url"),t&&this.logger.setLevel(t.toUpperCase()),n)&&this.notification.setBark(n),this.logger.info(e+", 开始执行!")}get isRequest(){return"undefined"!=typeof $request}get isStrictRequest(){return"undefined"!=typeof $request&&"undefined"==typeof $response}get isResponse(){return"undefined"!=typeof $response}get isDebug(){return"DEBUG"===this.logger.level}get request(){return"undefined"!=typeof $request?$request:void 0}get response(){if("undefined"!=typeof $response)return $response.hasOwnProperty("status")&&($response.statusCode=$response.status),$response.hasOwnProperty("statusCode")&&($response.status=$response.statusCode),$response}toStr(e,t=null){try{return JSON.stringify(e)}catch{return t}}toObj(e,t=null){try{return JSON.parse(e)}catch{return t}}checkRecordRequestBody(){if(this.isRequest){var t=$request.body;if(t){var n=this.env,r=$request.path;let e=this.scriptName+"#"+r.replace("/","_");e=e.replace("?","#"),n.isQuanX&&$prefs.setValueForKey(t,e),(n.isLoon||n.isSurge)&&$persistentStore.write(t,e),n.isNode&&require("fs").writeFileSync(e+".json",t,{flag:"w"},e=>console.log(e))}}}getRequestBody(){var e=this.env,t=$request.path;let n=this.scriptName+"#"+t.replace("/","_");if(n=n.replace("?","#"),e.isSurge||e.isLoon)return $persistentStore.read(n);if(e.isQuanX)return $prefs.valueForKey(n);if(e.isNode){t=n+".json",e=require("fs");if(!e.existsSync(t))return JSON.parse(e.readFileSync(t))}}getResponseBody(){if($response)return $response.body}parseCookies(e){let t={};return e&&e.split(";").forEach(function(e){e=e.split("=");t[e.shift().trim()]=decodeURI(e.join("="))}),t}serializeCookies(e){var t,n=[];for(t in e){var r=e[t],r=encodeURIComponent(t)+"="+encodeURIComponent(r);n.push(r)}return n.join("; ")}parseSetCookies(e){const o=["Expires","Max-Age","Domain","Path","HttpOnly","SameSite"];e=e.split(";");let i=null;const s={},a=[];return e.forEach(e=>{var t,e=e.trim();let n=null,r=!0;if(e.includes("=")?(t=e.split("="),n=t[0].trim(),r=t[1].trim()):n=e,o.includes(n))s[i]&&(s[i][n]=r,s[i].attribs[n]=r);else{i=n;let t={};i.includes(",")&&i.split(",").forEach(e=>{e=e.trim();o.includes(e)?t[e]=!0:i=e}),s[i]={name:i,value:r,attribs:t},a.push(s[i])}}),a}objToQueryStr(t,n){let r="";for(const o in t){let e=t[o];null!=e&&""!==e&&("object"==typeof e?e=JSON.stringify(e):n&&(e=encodeURIComponent(e)),r+=`${o}=${e}&`)}return r=r.substring(0,r.length-1)}parseQueryStr(e){var t={},n=(e=-1<e.indexOf("?")?e.split("?")[1]:e).split("&");for(let e=0;e<n.length;e++){var r=n[e].split("=");t[r[0]]=r[1]}return t}deepClone(e,t){for(var n in t=t||{},e)"object"==typeof e[n]?(t[n]=e[n].constructor===Array?[]:{},this.deepClone(e[n],t[n])):t[n]=e[n];return t}formatDate(e,t){var n,r={"M+":e.getMonth()+1,"d+":e.getDate(),"H+":e.getHours(),"m+":e.getMinutes(),"s+":e.getSeconds(),"q+":Math.floor((e.getMonth()+3)/3),S:e.getMilliseconds()};for(n in/(y+)/.test(t)&&(t=t.replace(RegExp.$1,(e.getFullYear()+"").substr(4-RegExp.$1.length))),r)new RegExp("("+n+")").test(t)&&(t=t.replace(RegExp.$1,1==RegExp.$1.length?r[n]:("00"+r[n]).substr((""+r[n]).length)));return t}parseDate(a,e){let l={y:0,M:1,d:0,H:0,h:0,m:0,s:0,S:0};(e=e||"yyyy-MM-dd").replace(/([^yMdHmsS]*?)(([yMdHmsS])\3*)([^yMdHmsS]*?)/g,function(e,t,n,r,o,i,s){return a=a.replace(new RegExp(t+"(\\d{"+n.length+"})"+o),function(e,t){return l[r]=parseInt(t),""}),""}),l.M--;e=new Date(l.y,l.M,l.d,l.H,l.m,l.s);return 0!==l.S&&e.setMilliseconds(l.S),e}costTime(){var e=this.scriptName+"执行完毕!",t=(this._endTime=(new Date).getTime(),this._endTime-this._startTime);this.logger.info(e+`耗时【${t/1e3}】秒`)}done=(e={})=>{this.costTime(),"undefined"!=typeof $done&&$done(e)}}(e,t)}function MagicHttp(d,g){var e;let p;d.isNode&&(e=require("axios"),p=e.create());class t{constructor(e=!0){this.handlers=[],this.isRequest=e}use(e,t,n){return"function"==typeof e&&g.debug("Register fulfilled "+e.name),"function"==typeof t&&g.debug("Register rejected "+t.name),this.handlers.push({fulfilled:e,rejected:t,synchronous:!(!n||"boolean"!=typeof n.synchronous)&&n.synchronous,runWhen:n?n.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}forEach(t){this.handlers.forEach(e=>{null!==e&&t(e)})}}function f(e){let n={...e};return n.params&&!d.isNode&&(e=Object.keys(n.params).map(e=>{var t=encodeURIComponent(e);return n.url=n.url.replace(new RegExp(e+"=[^&]*","ig"),""),n.url=n.url.replace(new RegExp(t+"=[^&]*","ig"),""),t+"="+encodeURIComponent(n.params[e])}).join("&"),n.url.indexOf("?")<0&&(n.url+="?"),/(&|\?)$/g.test(n.url)||(n.url+="&"),n.url+=e,delete n.params,g.debug("Params to QueryString: "+n.url)),n}const y=(e,t=null)=>{if(e){t={...e,config:e.config||t,status:e.statusCode||e.status,body:e.body||e.data,headers:e.headers||e.header};if("string"==typeof t.body)try{t.body=JSON.parse(t.body)}catch{}return delete t.data,t}return e};const h=(e,t=null)=>{if(e&&400<=e.status)return g.debug("Raise exception when status code is "+e.status),{name:"RequestException",message:"Request failed with status code "+e.status,config:t||e.config,response:e}},m={request:new t,response:new t(!1)};let v=[],b=[],S=!0;function N(e){return e=f(e),g.debug(`HTTP ${e.method.toUpperCase()}:`+"\n"+JSON.stringify(e)),e}function E(t){try{t=t&&y(t),g.sniffer(`HTTP ${t.config.method.toUpperCase()}:`+"\n"+JSON.stringify(t.config)+"\nSTATUS CODE:\n"+t.status+"\nRESPONSE:\n"+("object"==typeof t.body?JSON.stringify(t.body):t.body));var e=h(t);return e?Promise.reject(e):t}catch(e){return g.error(e),t}}const n=(e,n)=>{let r;n=((e,t)=>{let n="object"==typeof t?{headers:{},...t}:{url:t,headers:{}};return n.method||(n.method=e),!0===(n=f(n)).rewrite&&(d.isSurge?(n.headers["X-Surge-Skip-Scripting"]=!1,delete n.rewrite):d.isQuanX&&(n.hints=!1,delete n.rewrite)),d.isSurgeLike?(t=n.headers["content-type"]||n.headers["Content-Type"],"GET"!==n.method&&t&&0<=t.indexOf("application/json")&&n.body instanceof Array&&(n.body=JSON.stringify(n.body),g.debug("Convert Array object to String: "+n.body))):d.isQuanX?(n.hasOwnProperty("body")&&"string"!=typeof n.body&&(n.body=JSON.stringify(n.body)),n.method=e):d.isNode&&("POST"===e||"PUT"===e||"PATCH"===e||"DELETE"===e?n.data=n.data||n.body:"GET"===e&&(n.params=n.params||n.body),delete n.body),n})(e.toUpperCase(),n),r=d.isNode?p:d.isSurgeLike?i=>new Promise((r,o)=>{$httpClient[e.toLowerCase()](i,(e,t,n)=>{e?(e={name:e.name||e,message:e.message||e,stack:e.stack||e,config:i,response:y(t)},o(e)):(t.config=i,t.body=n,r(t))})}):r=>new Promise((n,t)=>{$task.fetch(r).then(e=>{e=y(e,r);var t=h(e,r);if(t)return Promise.reject(t);n(e)}).catch(e=>{e={name:e.message||e.error,message:e.message||e.error,stack:e.error,config:r,response:e.response?y(e.response):null};t(e)})});let o;var t=n;try{v=[],b=[],m.request.forEach(e=>{"function"==typeof e.runWhen&&!1===e.runWhen(t)||(S=S&&e.synchronous,v.unshift(e.fulfilled,e.rejected))}),m.response.forEach(e=>{b.push(e.fulfilled,e.rejected)})}catch(e){g.error(`Failed to register interceptors: ${e}.`)}var i=[N,void 0],s=[E,void 0];if(S){for(g.debug("Interceptors are executed in synchronous mode"),Array.prototype.unshift.apply(v,i),v=v.concat([N,void 0]);v.length;){var a=v.shift(),l=v.shift();try{"function"==typeof a&&g.debug("Executing request fulfilled "+a.name),n=a(n)}catch(e){"function"==typeof l&&g.debug("Executing request rejected "+l.name),l(e);break}}try{o=(!d.isNode&&n.timeout?c:r)(n)}catch(e){return Promise.reject(e)}for(Array.prototype.unshift.apply(b,s);b.length;)o=o.then(b.shift(),b.shift());return o}{g.debug("Interceptors are executed in asynchronous mode");let t=[r,void 0];for(Array.prototype.unshift.apply(t,i),Array.prototype.unshift.apply(t,v),t=(t=t.concat(s)).concat(b),o=Promise.resolve(n);t.length;)try{let e=t.shift();var u=t.shift();"function"==typeof(e=!d.isNode&&n.timeout&&e===r?c:e)&&g.debug("Executing request fulfilled "+e.name),"function"==typeof u&&g.debug("Executing request rejected "+u.name),o=o.then(e,u)}catch(e){g.error("request exception: "+e)}return o}function c(n){try{var e=new Promise((e,t)=>{setTimeout(()=>{var e={message:`timeout of ${n.timeout}ms exceeded.`,config:n};t(e)},n.timeout)});return Promise.race([r(n),e])}catch(e){g.error(`Request Timeout exception: ${e}.`)}}};return{request:n,interceptors:m,convertHeadersToLowerCase:n=>Object.keys(n).reduce((e,t)=>(e[t.toLowerCase()]=n[t],e),{}),convertHeadersToCamelCase:n=>Object.keys(n).reduce((e,t)=>{return e[t.split("-").map(e=>e[0].toUpperCase()+e.slice(1)).join("-")]=n[t],e},{}),modifyResponse:y,get:e=>n("GET",e),post:e=>n("POST",e),put:e=>n("PUT",e),patch:e=>n("PATCH",e),delete:e=>n("DELETE",e),head:e=>n("HEAD",e),options:e=>n("OPTIONS",e)}}function MagicData(d,g){let p={fs:void 0,data:{}};if(d.isNode){p.fs=require("fs");try{p.fs.accessSync("./magic.json",p.fs.constants.R_OK|p.fs.constants.W_OK)}catch(e){p.fs.writeFileSync("./magic.json","{}",{encoding:"utf8"})}p.data=require("./magic.json")}const s=(e,t)=>"object"!=typeof t&&e===t,a=e=>"true"===e||"false"!==e&&(void 0===e?null:e),l=(e,t,n,r)=>{if(n)try{e=!0===(e="string"==typeof e?JSON.parse(e):e).magic_session?e[n]:null}catch{e=null}if("string"==typeof e&&"null"!==e)try{e=JSON.parse(e)}catch{}return null==(e=!1===r&&e&&!0===e.magic_session?null:e)&&null!=t&&(e=t),e=a(e)},f=t=>{if("string"!=typeof t)return t instanceof Array||null==t||t!=t||"boolean"==typeof t?{}:t;{let e={};try{var n=typeof(e=JSON.parse(t));("object"!=n||e instanceof Array||"bool"==n||null===e)&&(e={})}catch{}return e}},u=(e,t=null,n="",r=!1,o=null)=>{let i="";return i=o||d.isNode?((e,t=null,n="",r=!1,o=null)=>{o=o||p.data;return val=o&&void 0!==o[e]&&null!==o[e]?o[e]:n?{}:null,val=l(val,t,n,r)})(e,t,n,r,o):(d.isSurgeLike?i=$persistentStore.read(e):d.isQuanX&&(i=$prefs.valueForKey(e)),l(i,t,n,r)),g.debug(`READ DATA [${e}]${n?`[${n}]`:""} <${typeof i}>`+"\n"+JSON.stringify(i)),i},c=(e,t,n="",r=null)=>{if(void 0===t||t!=t)return!1;d.isNode||"boolean"!=typeof t&&"number"!=typeof t||(t=String(t));let o="";var i,s,a,l,u,c;if(r||d.isNode?o=([i,s,a="",l=null]=[e,t,n,r],c=l||p.data,c=f(c),a?((u=f(c[i])).magic_session=!0,u[a]=s,c[i]=u):c[i]=s,null!==l&&(l=c),c):n?(d.isSurgeLike?o=$persistentStore.read(e)?$persistentStore.read(e):o:d.isQuanX&&(o=$prefs.valueForKey(e)?$prefs.valueForKey(e):o),(o=f(o)).magic_session=!0,o[n]=t):o=t,o&&"object"==typeof o&&(o=JSON.stringify(o,null,4)),g.debug(`WRITE DATA [${e}]${n?`[${n}]`:""} <${typeof t}>`+"\n"+JSON.stringify(t)),!r){if(d.isSurgeLike)return $persistentStore.write(o,e);if(d.isQuanX)return $prefs.setValueForKey(o,e);if(d.isNode)try{p.fs.writeFileSync("./magic.json",o)}catch(e){return g.error(e),!1}}return!0};return{read:u,write:c,del:(e,t="",n=null)=>{let r={};if(n||d.isNode)r=(o=e,i=t,s=n||p.data,s=f(s),i?(delete(obj=f(s[o]))[i],s[o]=obj):delete s[o],s),n?n=r:p.fs.writeFileSync("./magic.json",JSON.stringify(r,null,4));else if(t){d.isSurgeLike?r=$persistentStore.read(e):d.isQuanX&&(r=$prefs.valueForKey(e)),delete(r=f(r))[t];i=JSON.stringify(r,null,4);c(e,i)}else{if(d.isStorm)return $persistentStore.remove(e);if(d.isSurgeLike)return $persistentStore.write(null,e);if(d.isQuanX)return $prefs.removeValueForKey(e)}var o,i,s;g.debug(`DELETE KEY [${e}]`+(t?`[${t}]`:""))},update:(e,t,n,r=s,o=null)=>{var i;return t=a(t),!0!==r(u(e,null,n,!1,o),t)&&(i=c(e,t,n,o),e=u(e,null,n,!1,o),r===s&&"object"==typeof e?i:r(t,e))},allSessions:(e,t=null)=>{let n={};t=u(e,null,null,!0,t);return!0===(t=f(t)).magic_session&&delete(n={...t}).magic_session,g.debug(`READ ALL SESSIONS [${e}] <${typeof n}>`+"\n"+JSON.stringify(n,null,4)),n},allSessionNames:(e,t=null)=>{let n=[];t=u(e,null,null,!0,t),t=f(t);return n=!0!==t.magic_session?[]:Object.keys(t).filter(e=>"magic_session"!==e),g.debug(`READ ALL SESSIONS [${e}] <${typeof n}>`+"\n"+JSON.stringify(n,null,4)),n},defaultValueComparator:s,convertToObject:f}}function MagicNotification(i,o,s,a){let l=null,u=null,c=[];function d(e=i,t="",n="",r=""){r=(t=>{try{let e={};var n;return"string"==typeof t?0<t.length&&(o.isLoon?e={openUrl:t}:o.isQuanX?e={"open-url":t}:o.isSurge&&(e={url:t})):"object"==typeof t&&(o.isLoon?(e.openUrl=t["open-url"]||"",e.mediaUrl=t["media-url"]||""):o.isQuanX?e=t["open-url"]||t["media-url"]?t:{}:o.isSurge&&(n=t["open-url"]||t.openUrl,e=n?{url:n}:{})),e}catch(e){s.error("通知选项转换失败"+e)}return t})(r),1===arguments.length&&(e=i,t="",n=arguments[0]),s.notify("\ntitle:"+e+"\nsubTitle:"+t+"\nbody:"+n+"\noptions:"+("object"==typeof r?JSON.stringify(r):r)),o.isSurge?$notification.post(e,t,n,r):o.isLoon?r?$notification.post(e,t,n,r):$notification.post(e,t,n):o.isQuanX&&$notify(e,t,n,r),l&&u&&g(e,t,n)}function g(e=i,t="",n="",r){if(void 0===a||void 0===a.post)throw"Bark notification needs to import MagicHttp module.";e={url:l,headers:{"content-type":"application/json; charset=utf-8"},body:{title:e,body:t?t+"\n"+n:n,device_key:u}};a.post(e).catch(e=>{s.error("Bark notify error: "+e)})}return{post:d,debug:function(e=i,t="",n="",r=""){"DEBUG"===s.getLevel()&&(1===arguments.length&&(e=i,t="",n=arguments[0]),this.post(e,t,n,r))},bark:g,setBark:e=>{try{var t=e.replace(/\/+$/g,"");l=/^https?:\/\/([^/]*)/.exec(t)[0]+"/push",u=/\/([^\/]+)\/?$/.exec(t)[1]}catch(e){s.error(`Bark url error: ${e}.`)}},appendNotifyInfo:function(e,t){1==t?c=e:c.push(e)},prependNotifyInfo:function(e){c.splice(0,0,e)},msg:function(e,t,n,r){var o={};n&&(o["open-url"]=n),r&&(o["media-url"]=r),(t=t&&0!=t.length?t:Array.isArray(c)?c.join("\n"):c)&&0<t.length&&d(i,"",t,o)}}}function MagicUtils(r,u){const e=(e,t="yyyy-MM-dd hh:mm:ss")=>{var n,r={"M+":e.getMonth()+1,"d+":e.getDate(),"h+":e.getHours(),"m+":e.getMinutes(),"s+":e.getSeconds(),"q+":Math.floor((e.getMonth()+3)/3),S:e.getMilliseconds()};for(n in/(y+)/.test(t)&&(t=t.replace(RegExp.$1,(e.getFullYear()+"").substr(4-RegExp.$1.length))),r)new RegExp("("+n+")").test(t)&&(t=t.replace(RegExp.$1,1===RegExp.$1.length?r[n]:("00"+r[n]).substr((""+r[n]).length)));return t};return{retry:(i,s=5,a=0,l=null)=>(...e)=>new Promise((n,r)=>{function o(...t){Promise.resolve().then(()=>i.apply(this,t)).then(e=>{"function"==typeof l?Promise.resolve().then(()=>l(e)).then(()=>{n(e)}).catch(e=>{1<=s?0<a?setTimeout(()=>o.apply(this,t),a):o.apply(this,t):r(e),s--}):n(e)}).catch(e=>{u.error(e),1<=s&&0<a?setTimeout(()=>o.apply(this,t),a):1<=s?o.apply(this,t):r(e),s--})}o.apply(this,e)}),formatTime:e,now:()=>e(new Date,"yyyy-MM-dd hh:mm:ss"),today:()=>e(new Date,"yyyy-MM-dd"),sleep:t=>new Promise(e=>setTimeout(e,t)),assert:(e,t=null)=>{var n;r.isNode?(n=require("assert"),t?n(e,t):n(e)):!0!==e&&u.error("AssertionError: "+(t||"The expression evaluated to a falsy value."))}}}function MagicQingLong(e,a,o){let i="",s="",l="",u="",c="",t="";const d="magic.json",g=MagicHttp(e,o);async function n(){return l=l||a.read("magic_qlclient"),u=u||a.read("magic_qlsecrt"),s=s||a.read("magic_qlname"),c=c||a.read("magic_qlpwd"),i&&l&&u?(o.info("Get token from QingLong Panel"),await g.get({url:"/open/auth/token",headers:{"content-type":"application/json"},params:{client_id:l,client_secret:u}}).then(e=>{if(!(0<Object.keys(e.body).length&&e.body.data&&e.body.data.token))throw new Error("Get QingLong Panel token failed.");o.info("Successfully logged in to QingLong Panel"),t=e.body.data.token,a.write("magic_qltoken",t)}).catch(e=>{o.error("Error logging in to QingLong Panel.\n"+(e.message||e))})):i&&s&&c&&await g.post({url:"/api/user/login",headers:{"content-type":"application/json"},body:{username:s,password:c}}).then(e=>{o.info("Successfully logged in to QingLong Panel"),t=e.body.data.token,a.write("magic_qltoken",t)}).catch(e=>{o.error("Error logging in to QingLong Panel.\n"+(e.message||e))}),t}async function p(e){let t=[];return await g.post({url:"/api/envs",headers:{"content-type":"application/json"},body:e}).then(e=>{200===e.body.code?e.body.data.forEach(e=>{o.debug(`QINGLONG ADD ENV ${e.name} <${typeof e.value}> (${e.id})`+"\n"+JSON.stringify(e)),t.push(e.id)}):o.error("Error adding environments variable from QingLong Panel.\n"+JSON.stringify(e))}).catch(e=>{o.error("Error adding environments variable from QingLong Panel.\n"+(e.message||e))}),t}async function r(r=null,e="",t){let o=[];return await g.get({url:"/api/envs",headers:{"content-type":"application/json"},params:{searchValue:e}}).then(e=>{if(200!==e.body.code)throw new Error("Error reading environment variable from QingLong Panel.\n"+JSON.stringify(e));e=e.body.data;if(r){var t=[];for(const n of e)n.name===r&&o.push(n);o=t}o=e}).catch(e=>{throw new Error("Error reading environments variable from QingLong Panel.\n"+(e.message||e))}),o}async function f(e,t=""){let n="";return await g.get({url:"/api/scripts/"+e,params:{path:t}}).then(e=>{if(200!==e.body.code)throw new Error("Error reading data from QingLong Panel.\n"+JSON.stringify(e));n=e.body.data}).catch(e=>{throw new Error("Error reading data from QingLong Panel.\n"+(e.message||e))}),n}async function y(e,t="",n=""){let r=!1;return await g.put({url:"/api/scripts",headers:{"content-type":"application/json"},body:{filename:e,path:t,content:n}}).then(e=>{200===e.body.code?r=!0:o.error("Error reading data from QingLong Panel.\n"+JSON.stringify(e))}).catch(e=>{o.error("Error reading data from QingLong Panel.\n"+(e.message||e))}),r}return g.interceptors.request.use(function(e){return i=i||a.read("magic_qlurl"),e.url.indexOf(i)<0&&(e.url=""+i+e.url),{...e,timeout:3e3}},void 0),g.interceptors.request.use(function(e){return(l=l||a.read("magic_qlclient"))&&(e.url=e.url.replace("/api/","/open/")),e},void 0,{runWhen:e=>e.url.indexOf("api/user/login")<0&&e.url.indexOf("open/auth/token")<0}),g.interceptors.request.use(async function(e){return(t=t||a.read("magic_qltoken",""))||await n(),e.headers.authorization="Bearer "+t,e},void 0,{runWhen:e=>e.url.indexOf("api/user/login")<0&&e.url.indexOf("open/auth/token")<0}),g.interceptors.request.use(function(e){return e.params={...e.params,t:Date.now()},e},void 0,{runWhen:e=>e.url.indexOf("open/auth/token")<0}),g.interceptors.request.use(function(e){return i=i||a.read("magic_qlurl"),t=t||a.read("magic_qltoken"),o.debug("QingLong url: "+i+"\nQingLong token: "+t),e},void 0),g.interceptors.response.use(void 0,async function(e){try{var t=e.message||e.error||JSON.stringify(e);return(0<=t.indexOf("NSURLErrorDomain")&&0<=t.indexOf("-1012")||e.response&&401===e.response.status)&&e.config&&!0!==e.config.refreshToken?(o.warning("QingLong Panel token has expired"),o.info("Refreshing the QingLong Panel token"),await n(),e.config.refreshToken=!0,o.info("Call the previous method again"),await g.request(e.config.method,e.config)):Promise.reject(e)}catch(e){return Promise.reject(e)}}),{url:i||a.read("magic_qlurl"),init:(e,t,n,r,o)=>{i=e,l=t,u=n,s=r,c=o},getToken:n,setEnv:async function(t,n,r=null){if(i=i||a.read("magic_qlurl"),null===r){var e=await p([{name:t,value:n}]);if(e&&1===e.length)return e[0]}else await g.put({url:"/api/envs",headers:{"content-type":"application/json"},body:{name:t,value:n,id:r}}).then(e=>{if(200===e.body.code)return o.debug(`QINGLONG UPDATE ENV ${t} <${typeof n}> (${r})`+"\n"+JSON.stringify(n)),!0;o.error("Error adding environment variable from QingLong Panel.\n"+JSON.stringify(e))}).catch(e=>(o.error("Error adding environment variable from QingLong Panel.\n"+(e.message||e)),!1))},setEnvs:p,getEnv:async function(e){let t=null;for(const n of await r())if(n.id===e){t=n;break}return t},getEnvs:r,delEnvs:async function(t){return g.delete({url:"/api/envs",headers:{accept:"application/json","accept-language":"zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",connection:"keep-alive","content-type":"application/json;charset=UTF-8","user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.63 Safari/537.36 Edg/102.0.1245.30"},body:t}).then(e=>200===e.body.code?(o.debug("QINGLONG DELETE ENV IDS: "+t),!0):(o.error("Error deleting environments variable from QingLong Panel.\n"+JSON.stringify(e)),!1)).catch(e=>{o.error("Error deleting environments variable from QingLong Panel.\n"+(e.message||e))})},disableEnvs:async function(t){let n=!1;return await g.put({url:"/api/envs/disable",headers:{accept:"application/json","accept-Language":"zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",connection:"keep-alive","content-type":"application/json;charset=UTF-8","user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.63 Safari/537.36 Edg/102.0.1245.30"},body:t}).then(e=>{200===e.body.code?(o.debug("QINGLONG DISABLED ENV IDS: "+t),n=!0):o.error("Error disabling environments variable from QingLong Panel.\n"+JSON.stringify(e))}).catch(e=>{o.error("Error disabling environments variable from QingLong Panel.\n"+(e.message||e))}),n},enableEnvs:async function(t){let n=!1;return await g.put({url:"/api/envs/enable",headers:{accept:"application/json","accept-language":"zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",connection:"keep-alive","content-type":"application/json;charset=UTF-8","user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.63 Safari/537.36 Edg/102.0.1245.30"},body:t}).then(e=>{200===e.body.code?(o.debug("QINGLONG ENABLED ENV IDS: "+t),n=!0):o.error("Error enabling environments variable from Qilong panel.\n"+JSON.stringify(e))}).catch(e=>{o.error("Error enabling environments variable from Qilong panel.\n"+(e.message||e))}),n},addScript:async function(e,t="",n=""){let r=!1;return await g.post({url:"/api/scripts",headers:{"content-type":"application/json"},body:{filename:e,path:t,content:n}}).then(e=>{200===e.body.code?r=!0:o.error("Error reading data from QingLong Panel.\n"+JSON.stringify(e))}).catch(e=>{o.error("Error reading data from QingLong Panel.\n"+(e.message||e))}),r},getScript:f,editScript:y,delScript:async function(e,t=""){let n=!1;return await g.delete({url:"/api/scripts",headers:{"content-type":"application/json"},body:{filename:e,path:t}}).then(e=>{200===e.body.code?n=!0:o.error("Error reading data from QingLong Panel.\n"+JSON.stringify(e))}).catch(e=>{o.error("Error reading data from QingLong Panel.\n"+(e.message||e))}),n},write:async function(e,t,n=""){var r=await f(d,""),o=a.convertToObject(r),e=a.write(e,t,n,o),r=JSON.stringify(o,null,4);return await y(d,"",r)&&e},read:async function(e,t,n="",r=!1){var o=await f(d,""),o=a.convertToObject(o);return a.read(e,t,n,r,o)},del:async function(e,t=""){var n=await f(d,""),r=a.convertToObject(n),e=a.del(e,t,r),n=JSON.stringify(r,null,4),t=await y(d,"",n);return e&&t},update:async function(e,t,n,r=a.defaultValueComparator){var o=await f(d,""),i=a.convertToObject(o),e=a.update(e,t,n,r,i);let s=!1;return!0===e&&(o=JSON.stringify(i,null,4),s=await y(d,"",o)),e&&s},batchWrite:async function(...e){var t,n=await f(d,""),r=a.convertToObject(n);for(t of e)a.write(t[0],t[1],void 0!==t[2]?t[2]:"",r);return n=JSON.stringify(r,null,4),y(d,"",n)},batchRead:async function(...e){var t,n=await f(d,""),r=a.convertToObject(n),o=[];for(t of e){var i=a.read(t[0],t[1],void 0!==t[2]?t[2]:"","boolean"==typeof t[3]&&t[3],r);o.push(i)}return o},batchUpdate:async function(...e){var t,n=await f(d,""),r=a.convertToObject(n);for(t of e)a.update(t[0],t[1],void 0!==t[2]?t[2]:"",void 0!==t[3]?t.comparator:a.defaultValueComparator,r);return n=JSON.stringify(r,null,4),y(d,"",n)},batchDel:async function(...e){var t,n=await f(d,""),r=a.convertToObject(n);for(t of e)a.del(t[0],void 0!==t[1]?t[1]:"",r);return n=JSON.stringify(r,null,4),y(d,"",n)},allSessions:async function(e){var t=await f(d,""),t=a.convertToObject(t);return a.allSessions(e,t)},allSessionNames:async function(e){var t=await f(d,""),t=a.convertToObject(t);return a.allSessionNames(e,t)}}}
  1126. //---SyncByPyScript---MagicJS3-end
  1127. //---SyncByPyScript---md5-start
  1128. !function(n){"use strict";function d(n,t){var r=(65535&n)+(65535&t);return(n>>16)+(t>>16)+(r>>16)<<16|65535&r}function f(n,t,r,e,o,u){return d((u=d(d(t,n),d(e,u)))<<o|u>>>32-o,r)}function l(n,t,r,e,o,u,c){return f(t&r|~t&e,n,t,o,u,c)}function g(n,t,r,e,o,u,c){return f(t&e|r&~e,n,t,o,u,c)}function v(n,t,r,e,o,u,c){return f(t^r^e,n,t,o,u,c)}function m(n,t,r,e,o,u,c){return f(r^(t|~e),n,t,o,u,c)}function c(n,t){var r,e,o,u;n[t>>5]|=128<<t%32,n[14+(t+64>>>9<<4)]=t;for(var c=1732584193,f=-271733879,i=-1732584194,a=271733878,h=0;h<n.length;h+=16)c=l(r=c,e=f,o=i,u=a,n[h],7,-680876936),a=l(a,c,f,i,n[h+1],12,-389564586),i=l(i,a,c,f,n[h+2],17,606105819),f=l(f,i,a,c,n[h+3],22,-1044525330),c=l(c,f,i,a,n[h+4],7,-176418897),a=l(a,c,f,i,n[h+5],12,1200080426),i=l(i,a,c,f,n[h+6],17,-1473231341),f=l(f,i,a,c,n[h+7],22,-45705983),c=l(c,f,i,a,n[h+8],7,1770035416),a=l(a,c,f,i,n[h+9],12,-1958414417),i=l(i,a,c,f,n[h+10],17,-42063),f=l(f,i,a,c,n[h+11],22,-1990404162),c=l(c,f,i,a,n[h+12],7,1804603682),a=l(a,c,f,i,n[h+13],12,-40341101),i=l(i,a,c,f,n[h+14],17,-1502002290),c=g(c,f=l(f,i,a,c,n[h+15],22,1236535329),i,a,n[h+1],5,-165796510),a=g(a,c,f,i,n[h+6],9,-1069501632),i=g(i,a,c,f,n[h+11],14,643717713),f=g(f,i,a,c,n[h],20,-373897302),c=g(c,f,i,a,n[h+5],5,-701558691),a=g(a,c,f,i,n[h+10],9,38016083),i=g(i,a,c,f,n[h+15],14,-660478335),f=g(f,i,a,c,n[h+4],20,-405537848),c=g(c,f,i,a,n[h+9],5,568446438),a=g(a,c,f,i,n[h+14],9,-1019803690),i=g(i,a,c,f,n[h+3],14,-187363961),f=g(f,i,a,c,n[h+8],20,1163531501),c=g(c,f,i,a,n[h+13],5,-1444681467),a=g(a,c,f,i,n[h+2],9,-51403784),i=g(i,a,c,f,n[h+7],14,1735328473),c=v(c,f=g(f,i,a,c,n[h+12],20,-1926607734),i,a,n[h+5],4,-378558),a=v(a,c,f,i,n[h+8],11,-2022574463),i=v(i,a,c,f,n[h+11],16,1839030562),f=v(f,i,a,c,n[h+14],23,-35309556),c=v(c,f,i,a,n[h+1],4,-1530992060),a=v(a,c,f,i,n[h+4],11,1272893353),i=v(i,a,c,f,n[h+7],16,-155497632),f=v(f,i,a,c,n[h+10],23,-1094730640),c=v(c,f,i,a,n[h+13],4,681279174),a=v(a,c,f,i,n[h],11,-358537222),i=v(i,a,c,f,n[h+3],16,-722521979),f=v(f,i,a,c,n[h+6],23,76029189),c=v(c,f,i,a,n[h+9],4,-640364487),a=v(a,c,f,i,n[h+12],11,-421815835),i=v(i,a,c,f,n[h+15],16,530742520),c=m(c,f=v(f,i,a,c,n[h+2],23,-995338651),i,a,n[h],6,-198630844),a=m(a,c,f,i,n[h+7],10,1126891415),i=m(i,a,c,f,n[h+14],15,-1416354905),f=m(f,i,a,c,n[h+5],21,-57434055),c=m(c,f,i,a,n[h+12],6,1700485571),a=m(a,c,f,i,n[h+3],10,-1894986606),i=m(i,a,c,f,n[h+10],15,-1051523),f=m(f,i,a,c,n[h+1],21,-2054922799),c=m(c,f,i,a,n[h+8],6,1873313359),a=m(a,c,f,i,n[h+15],10,-30611744),i=m(i,a,c,f,n[h+6],15,-1560198380),f=m(f,i,a,c,n[h+13],21,1309151649),c=m(c,f,i,a,n[h+4],6,-145523070),a=m(a,c,f,i,n[h+11],10,-1120210379),i=m(i,a,c,f,n[h+2],15,718787259),f=m(f,i,a,c,n[h+9],21,-343485551),c=d(c,r),f=d(f,e),i=d(i,o),a=d(a,u);return[c,f,i,a]}function i(n){for(var t="",r=32*n.length,e=0;e<r;e+=8)t+=String.fromCharCode(n[e>>5]>>>e%32&255);return t}function a(n){var t=[];for(t[(n.length>>2)-1]=void 0,e=0;e<t.length;e+=1)t[e]=0;for(var r=8*n.length,e=0;e<r;e+=8)t[e>>5]|=(255&n.charCodeAt(e/8))<<e%32;return t}function e(n){for(var t,r="0123456789abcdef",e="",o=0;o<n.length;o+=1)t=n.charCodeAt(o),e+=r.charAt(t>>>4&15)+r.charAt(15&t);return e}function r(n){return unescape(encodeURIComponent(n))}function o(n){return i(c(a(n=r(n)),8*n.length))}function u(n,t){return function(n,t){var r,e=a(n),o=[],u=[];for(o[15]=u[15]=void 0,16<e.length&&(e=c(e,8*n.length)),r=0;r<16;r+=1)o[r]=909522486^e[r],u[r]=1549556828^e[r];return t=c(o.concat(a(t)),512+8*t.length),i(c(u.concat(t),640))}(r(n),r(t))}function t(n,t,r){return t?r?u(t,n):e(u(t,n)):r?o(n):e(o(n))}"function"==typeof define&&define.amd?define(function(){return t}):"object"==typeof module&&module.exports?module.exports=t:n.md5=t}(this);
  1129. //---SyncByPyScript---md5-end