bilibiliHelper.js 76 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195
  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. magicJS.done();
  96. }
  97. async function checkHandleRequest(){
  98. const request = magicJS.request;
  99. let cookieStr = request.headers.cookie || request.headers.Cookie;
  100. if(cookieStr){
  101. config.cookie = magicJS.parseCookies(cookieStr);
  102. const PStoreConfig = magicJS.data.read("bilibili_daily_bonus", {})
  103. if (PStoreConfig.cookie && PStoreConfig.cookie.bili_jct !== config.cookie.bili_jct) {
  104. if (PStoreConfig.Settings) config.Settings = PStoreConfig.Settings // 同步boxjs数据
  105. config.FirstInsert = false;
  106. magicJS.logger.info(magicJS.toStr(config));
  107. await persistentStore(config)
  108. } else if (PStoreConfig.cookie) {
  109. magicJS.logger.info("- cookie未失效,无需更新");
  110. } else {
  111. config.FirstInsert = true;
  112. await persistentStore(config);
  113. }
  114. }
  115. }
  116. async function persistentStore(config){
  117. if (config.cookie.DedeUserID) {
  118. const url = $request.url;
  119. config.key = url.match(/.*access_key=(.*?)&build/)?.[1];
  120. 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}`;
  121. if (!config.key) { //网页方式登录
  122. let auth_code = "0", access_key = "0", login_confirm = false;
  123. auth_code = await getAuthCode();
  124. if (auth_code !== "0"){
  125. login_confirm = await loginConfirm(auth_code)
  126. }
  127. if (login_confirm){
  128. access_key = await getAccessKey(auth_code)
  129. }
  130. if (access_key !== "0") {
  131. config.key = access_key
  132. } else {
  133. magicJS.logger.info("- 获取用户access_key失败!");
  134. magicJS.notification.post(magicJS.scriptName, "🤒获取用户access_key失败!");
  135. }
  136. }
  137. const isFirstInsert = config.FirstInsert;
  138. delete config.FirstInsert;
  139. magicJS.logger.info(magicJS.toStr(config))
  140. const successMessage = magicJS.data.write("bilibili_daily_bonus", magicJS.toStr(config))
  141. ? "🎉cookie存储成功"
  142. : "🤒cookie存储失败"
  143. magicJS.notification.post(magicJS.scriptName, isFirstInsert ? "首次获取cookie" : "检测到cookie已更新", successMessage);
  144. } else {
  145. magicJS.notification.post(magicJS.scriptName, "- 尚未登录, 请登录后重新获取cookie");
  146. }
  147. }
  148. async function signBiliBili() {
  149. config = magicJS.data.read("bilibili_daily_bonus", {});
  150. if (config.cookie && await me()) {
  151. await queryStatus();
  152. let exec_times = config.Settings?.exec; //用户设置投币次数
  153. if (!Boolean(exec_times)) {
  154. exec_times = 5;
  155. real_times = 5 - (Number(config.coins.num) / 10);
  156. } else {
  157. exec_times = Number(exec_times);
  158. real_times = Math.max(0, exec_times - (Number(config.coins.num) / 10));
  159. }
  160. let flag = isFlag(exec_times);
  161. if (flag){
  162. await dynamic();
  163. if (cards.length) {
  164. let item = cards[Math.floor(Math.random() * cards.length)];
  165. let card = magicJS.toObj(item.card);
  166. short_link = encodeURIComponent(card?.short_link_v2.replace(/\\\//g, '/'));
  167. await watch(item.desc.rid, item.desc.bvid, card.cid);
  168. await share(item.desc.rid, card.cid, short_link);
  169. } else {
  170. magicJS.logger.info("- 获取视频失败,请重试或寻求帮助");
  171. }
  172. magicJS.logger.info("3️⃣ 投币任务");
  173. if (typeof config.coins.failures !== 'undefined' && config.coins.failures > 0){
  174. config.coins.failures = 0; //重置投币失败次数
  175. }
  176. if (real_times === 0){
  177. magicJS.logger.info(`- 今日已完成 ${config.coins.time}`);
  178. } else {
  179. for (let i = 0; i < real_times; i ++) {
  180. if (Math.floor(config.user.money) <= 5) {
  181. magicJS.logger.info("- 硬币不足,投币失败");
  182. break;
  183. } else {
  184. await coin();
  185. await magicJS.utils.sleep(300) //减少频繁请求概率
  186. }
  187. }
  188. }
  189. magicJS.logger.info("---- 将尝试额外任务")
  190. } else {
  191. magicJS.logger.info("---- 经验值任务均已完成,将尝试额外任务")
  192. }
  193. await liveSign()
  194. await silver2coin()
  195. await vipScoreSign()
  196. if (config.user.vipStatus === 1) {
  197. await vipExtraEx()
  198. await vipScoreGo()
  199. await vipScoreFan()
  200. await vipScoreMovie()
  201. await vipScoreDress()
  202. await vipWatchAccept()
  203. //B币券每月尝试两次领取
  204. let day = magicJS.utils.formatTime(new Date(), 'dd');
  205. if (day === '1' || day === '15') {
  206. if (config.user.vipType === 2) {
  207. await vipPrivilege(1)
  208. await magicJS.utils.sleep(800) //延迟执行,防止领劵延迟
  209. let charge_mid = config.Settings?.charge_mid || config.user.mid //用户设置充电id
  210. let bp_num = config.Settings?.bp_num || 5 //用户设置充电数量
  211. await Charge(charge_mid, bp_num)//充电
  212. for (let i = 2; i <= 7; i++) await vipPrivilege(i)
  213. } else if (config.user.vipType === 1) {
  214. await vipPrivilege(6)
  215. await vipPrivilege(7)
  216. }
  217. }
  218. }
  219. flag = !isFlag(exec_times)
  220. let title = `登录${config.user.num}/观看${config.watch.num}/分享${config.share.num}/投币${config.coins.num / 10}${flag ? "已完成" : "未完成"}`
  221. magicJS.logger.info(`#### ${title}`)
  222. magicJS.logger.info(`- 登录时间: ${config.user.time || "暂无"}`)
  223. magicJS.logger.info(`- 观看时间: ${config.watch.time || "暂无"}`)
  224. magicJS.logger.info(`- 分享时间: ${config.share.time || "暂无"}`)
  225. magicJS.logger.info(`- 投币时间: ${config.coins.time || "暂无"}`)
  226. notice = {
  227. title: `[${config.user.uname}]`,
  228. subTitle: `${flag ? "✅任务完成" : "❗️有未完成的任务"}`,
  229. content:
  230. `任务:登录(观看)${check("watch") ? "" : "+10exp"} 分享${check("share") ? "" : "+5exp"} 投币${check("coins") ? "" : "+50exp"}\n` +
  231. `经验:当前${config.user.level_info.current_exp}/下级${config.user.level_info.next_exp}/满级28800\n` +
  232. `等级:当前${config.user.level_info.current_level}级 升满级最快需${Math.ceil((config.user.v6_exp)/65)}天`,
  233. }
  234. magicJS.notification.post(notice.title, notice.subTitle, notice.content)
  235. } else {
  236. magicJS.notification.post(`任务失败`,`📅 ${startTime}`, "🤒请更新cookie")
  237. }
  238. }
  239. async function getAuthCode() {
  240. const body = {
  241. appkey: "27eb53fc9058f8c3",
  242. local_id: 0,
  243. ts: getTimestamp()
  244. }
  245. const sortedBody = magicJS.objToQueryStr(Object.fromEntries(new Map(Array.from(Object.entries(body)).sort())))
  246. const sign = md5(sortedBody + 'c2ed53a74eeefe3cf99fbd01d8c9c375')
  247. body['sign'] = sign
  248. const myRequest = {
  249. url: "https://passport.bilibili.com/x/passport-tv-login/qrcode/auth_code",
  250. headers: {
  251. "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
  252. },
  253. body: magicJS.objToQueryStr(body)
  254. }
  255. return await magicJS.http.get(myRequest).then(response => {
  256. try {
  257. const body = response.body;
  258. if (body.code === 0 && body.message === "0") {
  259. magicJS.logger.info("- 获取auth_code成功")
  260. return body.data.auth_code
  261. } else {
  262. magicJS.logger.info("- 获取auth_code失败")
  263. return "0"
  264. }
  265. } catch (e) {
  266. magicJS.logger.error(JSON.stringify(e));
  267. }
  268. })
  269. }
  270. async function loginConfirm(auth_code) {
  271. const body = {
  272. auth_code,
  273. build: 7082000,
  274. csrf: config.cookie.bili_jct
  275. }
  276. const myRequest = {
  277. url: "https://passport.bilibili.com/x/passport-tv-login/h5/qrcode/confirm",
  278. headers: {
  279. "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
  280. 'cookie': `DedeUserID=${config.cookie.DedeUserID}; SESSDATA=${config.cookie.SESSDATA}`
  281. },
  282. body: magicJS.objToQueryStr(body)
  283. }
  284. return await magicJS.http.get(myRequest).then(response => {
  285. try {
  286. const body = response.body;
  287. if (body.code === 0 && body.message === "0") {
  288. magicJS.logger.info("- 确认登录成功")
  289. return true
  290. } else {
  291. magicJS.logger.info("- 确认登录失败")
  292. return false
  293. }
  294. } catch (e) {
  295. magicJS.logger.error(JSON.stringify(e));
  296. }
  297. })
  298. }
  299. async function getAccessKey(auth_code) {
  300. const body = {
  301. appkey: "27eb53fc9058f8c3",
  302. auth_code,
  303. local_id: 0,
  304. ts: getTimestamp()
  305. }
  306. const sortedBody = magicJS.objToQueryStr(Object.fromEntries(new Map(Array.from(Object.entries(body)).sort())))
  307. const sign = md5(sortedBody + 'c2ed53a74eeefe3cf99fbd01d8c9c375')
  308. body['sign'] = sign
  309. const myRequest = {
  310. url: "https://passport.bilibili.com/x/passport-tv-login/qrcode/poll",
  311. headers: {
  312. "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
  313. },
  314. body: magicJS.objToQueryStr(body)
  315. }
  316. return await magicJS.http.get(myRequest).then(response => {
  317. try {
  318. const body = response.body;
  319. if (body.code === 0 && body.message === "0") {
  320. magicJS.logger.info("- 获取access_key成功")
  321. return body.data.access_token
  322. } else {
  323. magicJS.logger.info("- 获取access_key失败")
  324. return "0"
  325. }
  326. } catch (e) {
  327. magicJS.logger.error(JSON.stringify(e));
  328. }
  329. })
  330. }
  331. async function watch(aid, bvid, cid) {
  332. magicJS.logger.info("1️⃣ 观看(登录)任务")
  333. if (check("watch")) {
  334. magicJS.logger.info(`- 正在观看(登录)(${bvid})`)
  335. const body = {
  336. aid,
  337. cid,
  338. bvid,
  339. mid: config.user.mid,
  340. csrf: config.cookie.bili_jct,
  341. played_time : 1,
  342. real_played_time: 1,
  343. realtime: 1,
  344. start_ts: getTimestamp(),
  345. type: 3,
  346. dt: 2,
  347. play_type: 0,
  348. from_spmid: 0,
  349. spmid: 0,
  350. auto_continued_play: 0,
  351. refer_url: "https%3A%2F%2Ft.bilibili.com%2F",
  352. bsource: ""
  353. }
  354. const myRequest = {
  355. url: 'https://api.bilibili.com/x/click-interface/web/heartbeat',
  356. headers: {
  357. "cookie": config.cookieStr,
  358. "referrer": `https://www.bilibili.com/video/${bvid}`
  359. },
  360. body: magicJS.objToQueryStr(body)
  361. }
  362. await magicJS.http.get(myRequest).then(response => {
  363. const body = response.body;
  364. if (body?.code === 0) {
  365. magicJS.logger.info(`- 累计观看(登录)次数 ${(config.watch.num || 0) + 1}`)
  366. config.user.num = (config.user.num || 0) + 1
  367. config.watch.num = (config.watch.num || 0) + 1
  368. magicJS.data.write("bilibili_daily_bonus", magicJS.toStr(config))
  369. } else {
  370. magicJS.logger.info("- 观看失败, 失败原因: " + body?.message)
  371. }
  372. })
  373. } else {
  374. magicJS.logger.info(`- 今日已经观看 ${config.watch.time}`)
  375. }
  376. }
  377. async function share(aid, cid, short_link) {
  378. magicJS.logger.info("2️⃣ 分享任务")
  379. if (check("share")) {
  380. magicJS.logger.info("- 正在分享, aid=" + aid)
  381. const body = {
  382. access_key: config.key.replace(/&actionKey=.*?&appkey=.*$/, ''),
  383. actionKey: 'appkey',
  384. appkey: '27eb53fc9058f8c3',
  385. build: '72700100',
  386. c_locale: 'zh-Hans_CN',
  387. device: 'phone',
  388. disable_rcmd: 0,
  389. link: short_link,
  390. mobi_app: 'iphone',
  391. object_extra_fields: '%7B%7D',
  392. oid: aid,
  393. panel_type: 1,
  394. platform: 'ios',
  395. s_locale:'zh-Hans_CN',
  396. share_channel: 'WEIXIN',
  397. share_id: 'main.ugc-video-detail.0.0.pv',
  398. share_origin: 'vinfo_share',
  399. sid: cid,
  400. spm_id: 'main.ugc-video-detail.0.0',
  401. statistics: '%7B%22appId%22%3A1%2C%22version%22%3A%227.27.0%22%2C%22abtest%22%3A%22%22%2C%22platform%22%3A1%7D',
  402. success: 1,
  403. ts: getTimestamp()
  404. }
  405. const sign = md5(magicJS.objToQueryStr(body) + 'c2ed53a74eeefe3cf99fbd01d8c9c375')
  406. body['sign'] = sign
  407. const myRequest = {
  408. url: 'https://api.bilibili.com/x/share/finish',
  409. headers: {},
  410. body: magicJS.objToQueryStr(Object.fromEntries(new Map(Array.from(Object.entries(body)).sort())))
  411. }
  412. await magicJS.http.get(myRequest).then(response => {
  413. const body = response.body;
  414. if (body?.code === 0) {
  415. config.share.num = (config.share.num || 0) + 1
  416. magicJS.logger.info("- 分享成功")
  417. magicJS.data.write("bilibili_daily_bonus", magicJS.toStr(config))
  418. } else {
  419. magicJS.logger.info("- 分享失败, 失败原因: " + body?.message)
  420. }
  421. })
  422. } else {
  423. magicJS.logger.info(`- 今日已经分享 ${config.share.time}`)
  424. }
  425. }
  426. async function coin() {
  427. if (config.coins.num >= 50) {
  428. magicJS.logger.info(`- 今日已完成 ${config.coins.time}`)
  429. return
  430. }
  431. let like_uid_list = await getFavUid()
  432. if (like_uid_list && like_uid_list.length > 0) {
  433. let aid = await getFavAid(like_uid_list)
  434. //magicJS.logger.info("即将投币的视频aid: " + aid)
  435. if (aid !== 0) {
  436. const body = {
  437. aid,
  438. multiply: 1,
  439. select_like: 0,
  440. cross_domain: true,
  441. csrf: config.cookie.bili_jct
  442. }
  443. const myRequest = {
  444. url: "https://api.bilibili.com/x/web-interface/coin/add",
  445. headers: {
  446. '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',
  447. 'accept': 'application/json, text/plain, */*',
  448. 'content-type': 'application/x-www-form-urlencoded',
  449. 'origin': 'https://www.bilibili.com',
  450. 'referer': 'https://www.bilibili.com/video/BV1MT411G7fG?vd_source=1970993e2eff4af7be029aefcfa468b8',
  451. 'cookie': config.cookieStr + ';buvid3=fuckchenruilovelaoliu'
  452. },
  453. body: magicJS.objToQueryStr(body)
  454. }
  455. await magicJS.http.get(myRequest).then(async response => {
  456. try {
  457. const body = response.body;
  458. if (body?.code === 0 && body?.message === "0") {
  459. magicJS.logger.info("- 投币成功")
  460. config.user.money -= 1
  461. config.coins.num += 10
  462. magicJS.data.write("bilibili_daily_bonus", magicJS.toStr(config))
  463. } else {
  464. magicJS.logger.info("- 投币失败,失败原因 " + body.message)
  465. config.coins.failures = (config.coins.failures === 0 || typeof config.coins.failures === 'undefined' ? 1 : config.coins.failures + 1)
  466. magicJS.data.write("bilibili_daily_bonus", magicJS.toStr(config))
  467. if (config.coins.failures < 11) {
  468. magicJS.logger.info("- 正在重试...重试次数 " + (config.coins.failures - 1) + "(超过十次不再重试)")
  469. await coin()
  470. }
  471. }
  472. } catch (e) {
  473. magicJS.logger.error(JSON.stringify(e));
  474. }
  475. })
  476. } else {
  477. magicJS.logger.info("获取随机投币视频失败")
  478. }
  479. } else {
  480. magicJS.logger.info("获取随机关注用户列表失败")
  481. }
  482. }
  483. async function getFavUid() {
  484. const myRequest = {
  485. url: `https://api.bilibili.com/x/relation/followings?vmid=${config.cookie.DedeUserID}&ps=10&order_type=attention`,
  486. headers: {
  487. 'cookie': config.cookieStr
  488. }
  489. }
  490. return await magicJS.http.get(myRequest).then(response => {
  491. try {
  492. const body = response.body;
  493. let like_uid_list = new Array()
  494. if (body?.code === 0) {
  495. magicJS.logger.info("- 获取关注列表成功")
  496. let like_list = body?.data?.list
  497. for (let i = 0; i < like_list.length; i ++) {
  498. like_uid_list[i] = like_list[i].mid
  499. }
  500. return like_uid_list
  501. } else {
  502. magicJS.logger.info("- 获取关注列表成失败")
  503. magicJS.logger.info("- 失败原因 " + body?.message)
  504. return like_uid_list
  505. }
  506. } catch (e) {
  507. magicJS.logger.error(JSON.stringify(e));
  508. }
  509. })
  510. }
  511. async function getFavAid(arr) {
  512. //magicJS.logger.info("- 获取关注列表中的随机视频")
  513. let random_int = Math.floor((Math.random()*arr.length))
  514. let random_mid = arr[random_int]
  515. let wbiSigns = getWbiSigns({mid: random_mid})
  516. const myRequest = {
  517. url: `https://api.bilibili.com/x/space/wbi/arc/search?${wbiSigns}`,
  518. headers: {
  519. 'cookie': config.cookieStr
  520. }
  521. }
  522. return await magicJS.http.get(myRequest).then(response => {
  523. try {
  524. const body = response.body;
  525. if (body?.code === 0) {
  526. magicJS.logger.info("- 获取投币视频成功")
  527. let vlist = body.data?.list?.vlist
  528. let random_v_int = Math.floor((Math.random() * vlist.length))
  529. let aid = vlist[random_v_int]?.aid
  530. magicJS.logger.info("- 作者: " + vlist[random_v_int]['author'] + "; 视频标题: " + vlist[random_v_int]['title'])
  531. return aid
  532. } else {
  533. magicJS.logger.info("- 获取投币视频失败")
  534. magicJS.logger.info("- 失败原因 " + body?.message)
  535. return 0
  536. }
  537. } catch (e) {
  538. magicJS.logger.error(JSON.stringify(e));
  539. }
  540. }, reason => {
  541. magicJS.logger.info("- 获取投币视频失败")
  542. magicJS.logger.info("- 失败原因 " + magicJS.toStr(reason))
  543. return 0
  544. })
  545. }
  546. async function silver2coin() {
  547. magicJS.logger.info("#### 银瓜子兑换硬币任务")
  548. const body = {
  549. csrf: config.cookie.bili_jct,
  550. csrf_token: config.cookie.bili_jct
  551. }
  552. const myRequest = {
  553. url: "https://api.live.bilibili.com/xlive/revenue/v1/wallet/silver2coin",
  554. headers: {
  555. 'cookie': config.cookieStr
  556. },
  557. body: magicJS.objToQueryStr(body)
  558. }
  559. await magicJS.http.get(myRequest).then(response => {
  560. try {
  561. let result = response.body;
  562. let title = `银瓜子转硬币`;
  563. // 兑换成功
  564. if (result && result.code === 0) {
  565. let subTitle = `- ${result.message}`
  566. let detail = `- 成功兑换: ${result.data.coin} 个硬币\n当前银瓜子: ${result.data.silver} , 当前金瓜子: ${result.data.gold}`
  567. magicJS.logger.info(subTitle)
  568. magicJS.logger.info(detail)
  569. magicJS.notification.post(title, subTitle, detail)
  570. }
  571. // 兑换中止(重复兑换&银瓜子不足)
  572. else if (result && result.code === 403) {
  573. let subTitle = "- 未成功兑换"
  574. let detail = `- 原因: ${result.message}`
  575. magicJS.logger.info(subTitle)
  576. magicJS.logger.info(detail)
  577. magicJS.notification.post(title, subTitle, detail)
  578. }
  579. // 兑换失败
  580. else {
  581. let subTitle = "- 兑换失败"
  582. let detail = `- 原因: ${result.message}`
  583. magicJS.logger.info(subTitle)
  584. magicJS.logger.info(detail)
  585. magicJS.notification.post(title, subTitle, detail)
  586. }
  587. } catch (e) {
  588. magicJS.logger.error(JSON.stringify(e));
  589. }
  590. }).catch(err => {
  591. const msg = `兑换异常\n${JSON.stringify(err)}`;
  592. magicJS.logger.error(msg);
  593. reject(msg);
  594. });
  595. }
  596. async function liveSign() {
  597. magicJS.logger.info("#### 直播签到任务")
  598. const myRequest = {
  599. url: "https://api.live.bilibili.com/xlive/web-ucenter/v1/sign/DoSign",
  600. headers: {
  601. 'cookie': config.cookieStr
  602. }
  603. }
  604. await magicJS.http.get(myRequest).then(response => {
  605. try {
  606. let body = response.body;
  607. if (body?.code === 0) {
  608. magicJS.logger.info("- 签到成功")
  609. magicJS.logger.info(`签到奖励:${body.data.text},连续签到${body.data.hadSignDays}天`)
  610. } else if (body && body.code === 1011040){
  611. magicJS.logger.info("- 今日已完成")
  612. } else {
  613. magicJS.logger.info("- 签到失败")
  614. magicJS.logger.info("- 失败原因 " + body?.message)
  615. }
  616. } catch (e) {
  617. magicJS.logger.error(JSON.stringify(e));
  618. }
  619. })
  620. }
  621. async function vipScoreSign() {
  622. magicJS.logger.info("#### 大会员大积分签到任务")
  623. if (config.user.vipStatus === 0) {
  624. magicJS.logger.info("- 当前用户非大会员, 无法完成任务")
  625. } else {
  626. if (check("score")) {
  627. const myRequest = {
  628. url: "https://api.bilibili.com/pgc/activity/score/task/sign",
  629. method: "POST",
  630. headers: {
  631. 'Referer': 'https://big.bilibili.com/mobile/bigPoint/task',
  632. 'cookie': config.cookieStr
  633. }
  634. }
  635. await magicJS.http.get(myRequest).then(response => {
  636. try {
  637. const body = response.body;
  638. if (body?.code === 0 && body?.message === "success") {
  639. magicJS.logger.info("- 签到成功")
  640. config.score.time = startTime
  641. config.score.num = 1
  642. magicJS.data.write("bilibili_daily_bonus", magicJS.toStr(config))
  643. } else {
  644. magicJS.logger.info("- 签到失败")
  645. magicJS.logger.info("- 失败原因 " + body?.message)
  646. }
  647. } catch (e) {
  648. magicJS.logger.error(JSON.stringify(e));
  649. }
  650. })
  651. } else {
  652. magicJS.logger.info("- 今日已完成")
  653. }
  654. }
  655. }
  656. async function vipExtraEx() {
  657. magicJS.logger.info("#### 大会员每日额外经验值")
  658. const body = {
  659. csrf: config.cookie.bili_jct,
  660. ts: getTimestamp(),
  661. buvid: config.cookie.Buvid,
  662. mobi_app: 'iphone',
  663. platform: 'ios',
  664. appkey: '27eb53fc9058f8c3',
  665. access_key: config.key
  666. }
  667. const sortedBody = magicJS.objToQueryStr(Object.fromEntries(new Map(Array.from(Object.entries(body)).sort())))
  668. const sign = md5(sortedBody + 'c2ed53a74eeefe3cf99fbd01d8c9c375')
  669. body['sign'] = sign
  670. const myRequest = {
  671. url: "https://api.bilibili.com/x/vip/experience/add",
  672. headers: {
  673. 'accept': 'application/json, text/plain, */*',
  674. 'app-key': 'iphone'
  675. },
  676. body: magicJS.objToQueryStr(body)
  677. }
  678. await magicJS.http.get(myRequest).then(response => {
  679. try {
  680. const body = response.body;
  681. if (body?.code === 0 && body?.message === "0") {
  682. magicJS.logger.info("- 成功获得10经验值")
  683. } else {
  684. magicJS.logger.info("- 每日额外经验任务失败")
  685. magicJS.logger.info("- 失败原因 " + body?.message)
  686. }
  687. } catch (e) {
  688. magicJS.logger.error(JSON.stringify(e));
  689. }
  690. })
  691. }
  692. async function vipScoreGo() {
  693. magicJS.logger.info("#### 大会员浏览会员购10s任务")
  694. const myRequest = {
  695. url: "https://show.bilibili.com/api/activity/fire/common/event/dispatch",
  696. headers: {
  697. 'Content-Type' : 'application/json',
  698. 'Cookie': config.cookieStr
  699. },
  700. body: `{"eventId":"hevent_oy4b7h3epeb"}`
  701. }
  702. await magicJS.http.get(myRequest).then(response => {
  703. try {
  704. const body = response.body;
  705. if (body?.code === 0 && body?.message === "SUCCESS") {
  706. magicJS.logger.info("- 成功获得10点大积分")
  707. } else {
  708. magicJS.logger.info("- 浏览会员购任务失败")
  709. magicJS.logger.info("- 失败原因 " + body?.message)
  710. }
  711. } catch (e) {
  712. magicJS.logger.error(JSON.stringify(e));
  713. }
  714. })
  715. }
  716. async function vipScoreFan() {
  717. magicJS.logger.info("#### 大会员浏览追番频道10s任务")
  718. const myRequest = {
  719. url: `https://api.bilibili.com/pgc/activity/deliver/task/complete?access_key=${config.key}&position=jp_channel&sign=768d600feba34e6d1109e4157c0f0c5f&task_sign=557D1ACE13E9E81393259FFB621D6D0E`,
  720. method: "POST",
  721. headers: {}
  722. }
  723. await magicJS.http.get(myRequest).then(response => {
  724. try {
  725. const body = response.body;
  726. if (body?.code === 0 && body?.message === "success") {
  727. magicJS.logger.info("- 成功获得10点大积分")
  728. } else {
  729. magicJS.logger.info("- 浏览追番频道任务失败")
  730. magicJS.logger.info("- 失败原因 " + body?.message)
  731. }
  732. } catch (e) {
  733. magicJS.logger.error(JSON.stringify(e));
  734. }
  735. })
  736. }
  737. async function vipScoreMovie() {
  738. magicJS.logger.info("#### 大会员浏览影视频道10s任务")
  739. const myRequest = {
  740. url: `https://api.bilibili.com/pgc/activity/deliver/task/complete?access_key=${config.key}&position=tv_channel&sign=09ece1c295cb86d74778b93c59c0da3a&task_sign=B7DA5FAE25C39F53C62C03076CF2878B`,
  741. method: "POST",
  742. headers: {}
  743. }
  744. await magicJS.http.get(myRequest).then(response => {
  745. try {
  746. const body = response.body;
  747. if (body?.code === 0 && body?.message === "success") {
  748. magicJS.logger.info("- 成功获得10点大积分")
  749. } else {
  750. magicJS.logger.info("- 浏览影视频道任务失败")
  751. magicJS.logger.info("- 失败原因 " + body?.message)
  752. }
  753. } catch (e) {
  754. magicJS.logger.error(JSON.stringify(e));
  755. }
  756. })
  757. }
  758. async function vipScoreDress() {
  759. magicJS.logger.info("#### 大会员浏览装扮商城主页任务")
  760. const body = {
  761. csrf: config.cookie.bili_jct,
  762. ts: getTimestamp(),
  763. taskCode: 'dress-view',
  764. access_key: config.key
  765. }
  766. const myRequest = {
  767. url: 'https://api.bilibili.com/pgc/activity/score/task/complete/v2',
  768. headers: {},
  769. body: magicJS.objToQueryStr(body)
  770. }
  771. await magicJS.http.get(myRequest).then(response => {
  772. try {
  773. const body = response.body;
  774. if (body?.code === 0 && body?.message === "success") {
  775. magicJS.logger.info("- 成功获得10点大积分")
  776. } else {
  777. magicJS.logger.info("- 浏览装扮商城主页任务失败")
  778. }
  779. } catch (e) {
  780. magicJS.logger.error(JSON.stringify(e));
  781. }
  782. })
  783. }
  784. async function vipWatchAccept() {
  785. magicJS.logger.info("#### 接取大会员观看剧集10min任务")
  786. const body = {
  787. csrf: config.cookie.bili_jct,
  788. ts: getTimestamp(),
  789. taskCode: 'ogvwatchnew',
  790. mobi_app: 'iphone',
  791. platform: 'ios',
  792. appkey: '27eb53fc9058f8c3',
  793. access_key: config.key
  794. }
  795. const sortedBody = magicJS.objToQueryStr(Object.fromEntries(new Map(Array.from(Object.entries(body)).sort())))
  796. const sign = md5(sortedBody + 'c2ed53a74eeefe3cf99fbd01d8c9c375')
  797. body['sign'] = sign
  798. const myRequest = {
  799. url: 'https://api.bilibili.com/pgc/activity/score/task/receive/v2',
  800. headers: {
  801. 'Content-Type': 'application/x-www-form-urlencoded',
  802. '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',
  803. 'Cookie': `SESSDATA=${config.cookie.SESSDATA}`,
  804. 'Referer': `https://big.bilibili.com/mobile/bigPoint/task`
  805. },
  806. body: magicJS.objToQueryStr(body)
  807. }
  808. await magicJS.http.get(myRequest).then(response => {
  809. try {
  810. const body = response.body;
  811. if (body?.code === 0 && body?.message === "success") {
  812. magicJS.logger.info("- 大会员观看剧集任务接取成功, 需自行观看")
  813. } else {
  814. magicJS.logger.info("- 大会员观看剧集任务接取失败")
  815. magicJS.logger.info("- 失败原因 " + body?.message)
  816. }
  817. } catch (e) {
  818. magicJS.logger.error(JSON.stringify(e));
  819. }
  820. })
  821. }
  822. async function vipPrivilege(type) {
  823. magicJS.logger.info("#### 领取大会员月度福利")
  824. const body = {
  825. csrf: config.cookie.bili_jct,
  826. type
  827. }
  828. const myRequest = {
  829. url: 'https://api.bilibili.com/x/vip/privilege/receive',
  830. headers: {
  831. 'Cookie': config.cookieStr
  832. },
  833. body: magicJS.objToQueryStr(body)
  834. }
  835. await magicJS.http.get(myRequest).then(response => {
  836. try {
  837. const body = response.body;
  838. if (body?.code === 0) {
  839. switch (type) {
  840. case 1:
  841. magicJS.logger.info("- 领取年度大会员每月B币券成功")
  842. magicJS.notification.post("年度大会员月度福利", "B币券", "🎉🎉🎉领取成功")
  843. break
  844. case 2:
  845. magicJS.logger.info("- 领取年度大会员每月会员购优惠券成功")
  846. break
  847. case 3:
  848. magicJS.logger.info("- 领取年度大会员每月漫画福利券成功")
  849. break
  850. case 4:
  851. magicJS.logger.info("- 领取年度大会员每月会员购包邮券成功")
  852. break
  853. case 5:
  854. magicJS.logger.info("- 领取年度大会员每月漫画商城优惠券成功")
  855. break
  856. case 6:
  857. magicJS.logger.info("- 领取大会员每月装扮体验卡成功")
  858. break
  859. case 7:
  860. magicJS.logger.info("- 领取大会员每月课堂优惠券成功")
  861. break
  862. default:
  863. break
  864. }
  865. } else {
  866. magicJS.logger.info("- 领取大会员每月福利失败, 福利编码为" + type)
  867. magicJS.logger.info("- 失败原因 " + body?.message)
  868. if (type === 1) {
  869. magicJS.notification.post("年度大会员月度福利", "B币券领取失败", "失败原因为: " + body?.message)
  870. }
  871. //其他福利没什么用,失败也无需单独通知
  872. }
  873. } catch (e) {
  874. magicJS.logger.error(JSON.stringify(e));
  875. }
  876. })
  877. }
  878. async function Charge(mid, bp_num) {
  879. magicJS.logger.info("#### B币券自动充电")
  880. const body = {
  881. bp_num,
  882. is_bp_remains_prior: true,
  883. up_mid: mid,
  884. otype: 'up',
  885. oid: mid,
  886. csrf: config.cookie.bili_jct
  887. }
  888. const myRequest = {
  889. url: 'https://api.bilibili.com/x/ugcpay/web/v2/trade/elec/pay/quick',
  890. headers: {
  891. 'Cookie': config.cookieStr
  892. },
  893. body: magicJS.objToQueryStr(body)
  894. }
  895. await magicJS.http.get(myRequest).then(response => {
  896. try {
  897. const body = response.body;
  898. if (body?.code === 0) {
  899. if (body?.data?.status === 4) {
  900. if (mid === config.user.mid) {
  901. magicJS.logger.info("- 为自己充电成功")
  902. } else {
  903. magicJS.logger.info(`- 为用户id为${mid}的用户充电成功`)
  904. }
  905. } else if (body?.data?.status === -4) {
  906. magicJS.logger.info("- 充电失败, B币不足")
  907. } else {
  908. magicJS.logger.info("- 充电失败")
  909. magicJS.logger.info("- 失败原因 " + body?.message)
  910. }
  911. } else {
  912. magicJS.logger.info("- 充电失败")
  913. magicJS.logger.info("- 失败原因 " + body?.message)
  914. }
  915. } catch (e) {
  916. magicJS.logger.error(JSON.stringify(e));
  917. }
  918. })
  919. }
  920. async function me() {
  921. magicJS.logger.info("#### 用户信息")
  922. const myRequest = {
  923. url: 'https://api.bilibili.com/x/web-interface/nav',
  924. headers: {
  925. "cookie": config.cookieStr
  926. }
  927. }
  928. return await magicJS.http.get(myRequest).then(response => {
  929. try {
  930. const body = response.body;
  931. if (body?.code) {
  932. magicJS.logger.info("- ❌❌获得用户信息失败(请更新cookie)")
  933. magicJS.data.write("bilibili_daily_bonus", null)
  934. return false
  935. } else {
  936. magicJS.logger.info("- 🎉cookie有效任务即将开始🎉")
  937. config.user = body?.data
  938. config.user.num = check("user") ? 1 : (config.user.num || 0) + 1
  939. magicJS.data.write("bilibili_daily_bonus", magicJS.toStr(config))
  940. config.user.mext_exp = config.user.level_info.next_exp - config.user.level_info.current_exp
  941. config.user.next_day = Math.ceil(config.user.mext_exp / 15)
  942. config.user.v6_exp = 28800 - config.user.level_info.current_exp
  943. config.user.v6_day = Math.ceil(config.user.v6_exp / 15)
  944. if (config.user.vipStatus === 1) {
  945. magicJS.logger.info("- 💖尊贵的大会员用户💖")
  946. }
  947. magicJS.logger.info("- 用户名称: " + config.user.uname)
  948. magicJS.logger.info("- 用户ID: " + config.user.mid)
  949. magicJS.logger.info("- 用户硬币: " + Math.floor(config.user.money))
  950. magicJS.logger.info("- 用户B币: " + config.user.wallet.bcoin_balance)
  951. magicJS.logger.info("- 用户等级: " + config.user.level_info.current_level)
  952. magicJS.logger.info(
  953. `- 当前经验: ${config.user.level_info.current_exp}/${config.user.level_info.next_exp}`
  954. )
  955. magicJS.logger.info(`- 升级还需经验: ${config.user.mext_exp}`)
  956. magicJS.logger.info(
  957. `- 距离下级还需: ${config.user.next_day}天(登录 观看 分享)`
  958. )
  959. magicJS.logger.info(
  960. `- 距离满级还需: ${Math.max(0, config.user.v6_day)}天(登录 观看 分享)`
  961. )
  962. magicJS.logger.info(`- 剩余硬币最多可投: ${Math.floor((config.user.money)/5)}天`)
  963. magicJS.logger.info(
  964. "- 距离满级最快还需: " +
  965. Math.max(0, Math.ceil(config.user.v6_exp / 65)) +
  966. "天(日常 + 投币*5)"
  967. )
  968. return true
  969. }
  970. } catch (e) {
  971. magicJS.logger.error(JSON.stringify(e));
  972. }
  973. }, reason => {
  974. magicJS.notification.post(magicJS.scriptName, "- 获取用户信息失败", magicJS.toStr(reason))
  975. return false
  976. })
  977. }
  978. async function queryStatus() {
  979. magicJS.logger.info("#### 检查任务进行状况")
  980. const myRequest = {
  981. url: "https://api.bilibili.com/x/member/web/exp/reward",
  982. headers: {
  983. "cookie": config.cookieStr
  984. }
  985. }
  986. await magicJS.http.get(myRequest).then(response => {
  987. try {
  988. const body = response.body;
  989. if (body?.code === 0) {
  990. if (body.data.login) {
  991. magicJS.logger.info("- 今日已登录")
  992. config.user.num = (config.user.num === 0 ? 1 : config.user.num)
  993. if (!config['user'].hasOwnProperty("time")) {
  994. config.user.time = startTime
  995. }
  996. } else {
  997. magicJS.logger.info("! 今日尚未登录")
  998. config.user.num = 0
  999. }
  1000. if (body.data.watch){
  1001. magicJS.logger.info("- 今日已观看")
  1002. config.watch.num = (config.watch.num === 0 || typeof config.watch.num === 'undefined' ? 1 : config.watch.num)
  1003. if (!config['watch'].hasOwnProperty("time")) {
  1004. config.watch.time = startTime
  1005. }
  1006. } else {
  1007. magicJS.logger.info("! 今日尚未观看")
  1008. config.watch.num = 0
  1009. }
  1010. if (body.data.share){
  1011. magicJS.logger.info("- 今日已分享")
  1012. config.share.num = (config.share.num === 0 || typeof config.share.num === 'undefined' ? 1 : config.share.num)
  1013. if (!config['share'].hasOwnProperty("time")) {
  1014. config.share.time = startTime
  1015. }
  1016. } else {
  1017. magicJS.logger.info("! 今日尚未分享")
  1018. config.share.num = 0
  1019. }
  1020. if (body.data.coins === 50){
  1021. magicJS.logger.info("- 今日已投币")
  1022. if (!config['coins'].hasOwnProperty("time")) {
  1023. config.coins.time = startTime
  1024. } else {
  1025. if (format(new Date().toDateString()) > config.coins.time) {
  1026. config.coins.time = startTime
  1027. }
  1028. }
  1029. } else if ((body.data.coins / 10) >= real_times) {
  1030. config.coins.time = startTime
  1031. magicJS.logger.info("- 已完成用户设置的投币量")
  1032. } else if (config.user.money <= 5) {
  1033. magicJS.logger.info("! 硬币数不足")
  1034. } else {
  1035. magicJS.logger.info("! 今日投币未完成")
  1036. }
  1037. config.coins.num = body.data.coins
  1038. magicJS.data.write("bilibili_daily_bonus", magicJS.toStr(config))
  1039. } else {
  1040. magicJS.logger.info("- 查询失败")
  1041. magicJS.logger.info("- 失败原因 " + body?.message)
  1042. }
  1043. } catch (e) {
  1044. magicJS.logger.error(JSON.stringify(e));
  1045. }
  1046. })
  1047. }
  1048. async function dynamic() {
  1049. magicJS.logger.info("#### 获取首页视频")
  1050. const myRequest = {
  1051. url: `https://api.vc.bilibili.com/dynamic_svr/v1/dynamic_svr/dynamic_new?uid=${config.cookie.DedeUserID}&type_list=8&from=&platform=web`,
  1052. headers: {
  1053. "cookie": config.cookieStr
  1054. }
  1055. }
  1056. await magicJS.http.get(myRequest).then(response => {
  1057. try {
  1058. const body = response.body;
  1059. if (body?.data?.cards) {
  1060. cards = body.data.cards
  1061. const { user, watch, share } = config
  1062. user.time = watch.time = share.time = startTime
  1063. magicJS.logger.info("- 获取视频动态成功")
  1064. } else {
  1065. magicJS.logger.info("- 获取视频动态失败")
  1066. }
  1067. } catch (e) {
  1068. magicJS.logger.error(JSON.stringify(e));
  1069. }
  1070. })
  1071. }
  1072. // Wbi签名获取
  1073. function getWbiSigns(requestParams) {
  1074. // 从给定字符串生成特定的签名
  1075. function generateSignature(baseString) {
  1076. let signature = "";
  1077. signatureIndices.forEach(index => {
  1078. signature += baseString[index];
  1079. });
  1080. return signature.slice(0, 32);
  1081. }
  1082. // 主要函数来构建请求参数并生成最终的请求字符串
  1083. function buildRequestWithSignature(params, imageKey, subscriptionKey) {
  1084. const signatureBase = generateSignature(imageKey + subscriptionKey);
  1085. const startTimeInMillisecond = new Date().getTime();
  1086. const startTimeInSeconds = parseInt(startTimeInMillisecond / 1000);
  1087. let queryString = "";
  1088. // 添加时间戳到请求参数
  1089. params = Object.assign(params, {
  1090. wts: startTimeInSeconds
  1091. });
  1092. // 将参数对象转换为排序后的查询字符串
  1093. queryString = objectToQueryString(sortedObjectEntries(params));
  1094. // 生成请求ID并附加到查询字符串
  1095. const requestId = md5(queryString + signatureBase);
  1096. return queryString + "&w_rid=" + requestId;
  1097. }
  1098. // 转换对象为查询字符串
  1099. function objectToQueryString(obj) {
  1100. return magicJS.objToQueryStr(Object.fromEntries(new Map(Array.from(Object.entries(obj)).sort())));
  1101. }
  1102. // 获取图片和订阅的关键信息
  1103. function getImageAndSubscriptionKeys() {
  1104. const imageUrl = config.user.wbi_img.img_url;
  1105. const subscriptionUrl = config.user.wbi_img.sub_url;
  1106. return {
  1107. img_key: imageUrl.substring(imageUrl.lastIndexOf("/") + 1).split(".")[0],
  1108. sub_key: subscriptionUrl.substring(subscriptionUrl.lastIndexOf("/") + 1).split(".")[0]
  1109. };
  1110. }
  1111. // 签名索引数组
  1112. const signatureIndices = [
  1113. 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,
  1114. 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,
  1115. 57, 62, 11, 36, 20, 34, 44, 52
  1116. ];
  1117. // 提取图片和订阅关键信息
  1118. const { img_key, sub_key } = getImageAndSubscriptionKeys();
  1119. // 构建并返回请求字符串,包含签名
  1120. return buildRequestWithSignature(requestParams, img_key, sub_key);
  1121. }
  1122. // Main()
  1123. // .catch((e) => magicJS.logger.error(JSON.stringify(e)))
  1124. // .finally(() => magicJS.done());
  1125. Main();
  1126. //---SyncByPyScript---MagicJS3-start
  1127. 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)}}}
  1128. //---SyncByPyScript---MagicJS3-end
  1129. //---SyncByPyScript---md5-start
  1130. !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);
  1131. //---SyncByPyScript---md5-end