diff --git a/.github/workflows/baiduspeed.yml b/.github/workflows/baiduspeed.yml new file mode 100644 index 0000000000..0862f79337 --- /dev/null +++ b/.github/workflows/baiduspeed.yml @@ -0,0 +1,48 @@ + +name: 百度极速版 + +on: + workflow_dispatch: + schedule: + - cron: '*/30 * * * *' + watch: + types: started +jobs: + build: + runs-on: ubuntu-latest + if: github.event.repository.owner.id == github.event.sender.id + env: + BAIDU_COOKIE: ${{ secrets.BAIDU_COOKIE }} + TZ: Asia/shanghai + steps: + - name: Checkout + uses: actions/checkout@v2 + - name: Use Node.js 12.x + uses: actions/setup-node@v1 + with: + node-version: 12.x + - name: npm install + run: | + npm install + - name: '运行 【百度极速】' + if: env.BAIDU_COOKIE + run: | + node Task/baidu_speed.js + env: + BAIDU_CASH: ${{ secrets.BAIDU_CASH }} + BAIDU_TASK: ${{ secrets.BAIDU_TASK }} + PUSH_KEY: ${{ secrets.PUSH_KEY}} + BARK_PUSH: ${{ secrets.BARK_PUSH}} + BARK_SOUND: ${{ secrets.BARK_SOUND}} + TG_BOT_TOKEN: ${{ secrets.TG_BOT_TOKEN}} + TG_USER_ID: ${{ secrets.TG_USER_ID}} + DD_BOT_TOKEN: ${{ secrets.DD_BOT_TOKEN}} + DD_BOT_SECRET: ${{ secrets.DD_BOT_SECRET}} + QYWX_KEY: ${{ secrets.QYWX_KEY}} + IGOT_PUSH_KEY: ${{ secrets.IGOT_PUSH_KEY}} + QQ_SKEY: ${{ secrets.QQ_SKEY}} + QQ_MODE: ${{ secrets.QQ_MODE}} + PUSH_PLUS_TOKEN: ${{ secrets.PUSH_PLUS_TOKEN}} + PUSH_PLUS_USER: ${{ secrets.PUSH_PLUS_USER}} + TG_PROXY_HOST: ${{ secrets.TG_PROXY_HOST}} + TG_PROXY_PORT: ${{ secrets.TG_PROXY_PORT}} \ No newline at end of file diff --git a/.github/workflows/dianshijia.yml b/.github/workflows/dianshijia.yml index 3811697c12..761538a24b 100644 --- a/.github/workflows/dianshijia.yml +++ b/.github/workflows/dianshijia.yml @@ -1,10 +1,10 @@ -name: dianshijia +name: 电视家 on: workflow_dispatch: schedule: - - cron: '*/29 4,12,23 * * *' + - cron: '*/15 4,12,19,23 * * *' watch: types: started jobs: @@ -14,12 +14,14 @@ jobs: env: DSJ_HEADERS: ${{ secrets.DSJ_HEADERS }} DSJ_DRAWAL: ${{ secrets.DSJ_DRAWAL }} + TZ: Asia/shanghai steps: - - uses: actions/checkout@v1 - - name: Use Node.js 10.x + - name: Checkout + uses: actions/checkout@v2 + - name: Use Node.js 12.x uses: actions/setup-node@v1 with: - node-version: 10.x + node-version: 12.x - name: npm install run: | npm install @@ -29,10 +31,19 @@ jobs: node Task/dianshijia.js env: DSJ_NOTIFY_CONTROL: ${{ secrets.DSJ_NOTIFY_CONTROL }} - PUSH_KEY: ${{ secrets.PUSH_KEY }} - BARK_PUSH: ${{ secrets.BARK_PUSH }} - TG_BOT_TOKEN: ${{ secrets.TG_BOT_TOKEN }} - TG_USER_ID: ${{ secrets.TG_USER_ID }} - BARK_SOUND: ${{ secrets.BARK_SOUND }} - DD_BOT_TOKEN: ${{ secrets.DD_BOT_TOKEN }} - DD_BOT_SECRET: ${{ secrets.DD_BOT_SECRET }} \ No newline at end of file + PUSH_KEY: ${{ secrets.PUSH_KEY}} + BARK_PUSH: ${{ secrets.BARK_PUSH}} + BARK_SOUND: ${{ secrets.BARK_SOUND}} + TG_BOT_TOKEN: ${{ secrets.TG_BOT_TOKEN}} + TG_USER_ID: ${{ secrets.TG_USER_ID}} + DD_BOT_TOKEN: ${{ secrets.DD_BOT_TOKEN}} + DD_BOT_SECRET: ${{ secrets.DD_BOT_SECRET}} + QYWX_KEY: ${{ secrets.QYWX_KEY}} + IGOT_PUSH_KEY: ${{ secrets.IGOT_PUSH_KEY}} + QQ_SKEY: ${{ secrets.QQ_SKEY}} + QQ_MODE: ${{ secrets.QQ_MODE}} + PUSH_PLUS_TOKEN: ${{ secrets.PUSH_PLUS_TOKEN}} + PUSH_PLUS_USER: ${{ secrets.PUSH_PLUS_USER}} + TG_PROXY_HOST: ${{ secrets.TG_PROXY_HOST}} + TG_PROXY_PORT: ${{ secrets.TG_PROXY_PORT}} + \ No newline at end of file diff --git a/.github/workflows/jingxi.yml b/.github/workflows/jukan.yml similarity index 59% rename from .github/workflows/jingxi.yml rename to .github/workflows/jukan.yml index 6baff88bfa..2fd2676c16 100644 --- a/.github/workflows/jingxi.yml +++ b/.github/workflows/jukan.yml @@ -1,10 +1,9 @@ - -name: jingxi - +# 已禁用阅读任务,其他可行 +name: 聚看点 on: workflow_dispatch: schedule: - - cron: '5 5 * * *' + - cron: '*/20 */2 * * *' watch: types: started jobs: @@ -12,20 +11,22 @@ jobs: runs-on: ubuntu-latest if: github.event.repository.owner.id == github.event.sender.id env: - JD_COOKIE: ${{ secrets.JD_COOKIE }} + JUKAN_BODY: ${{ secrets.JUKAN_BODY }} + TZ: Asia/shanghai steps: - - uses: actions/checkout@v1 - - name: Use Node.js 10.x + - name: Checkout + uses: actions/checkout@v2 + - name: Use Node.js 12.x uses: actions/setup-node@v1 with: - node-version: 10.x + node-version: 12.x - name: npm install run: | npm install - - name: '运行 【京喜】' - if: env.JD_COOKIE + - name: '运行 【聚看点】' + if: env.JUKAN_BODY run: | - node Task/jingxi.js + node Task/jukan.js env: PUSH_KEY: ${{ secrets.PUSH_KEY }} BARK_PUSH: ${{ secrets.BARK_PUSH }} @@ -33,4 +34,4 @@ jobs: TG_USER_ID: ${{ secrets.TG_USER_ID }} BARK_SOUND: ${{ secrets.BARK_SOUND }} DD_BOT_TOKEN: ${{ secrets.DD_BOT_TOKEN }} - DD_BOT_SECRET: ${{ secrets.DD_BOT_SECRET }} \ No newline at end of file + DD_BOT_SECRET: ${{ secrets.DD_BOT_SECRET }} diff --git a/.github/workflows/kuaishou.yml b/.github/workflows/kuaishou.yml new file mode 100644 index 0000000000..63ff425be3 --- /dev/null +++ b/.github/workflows/kuaishou.yml @@ -0,0 +1,37 @@ +name: 快手视频签到 + +on: + workflow_dispatch: + schedule: + - cron: '1/20 10-23/3 * * *' + watch: + types: started +jobs: + build: + runs-on: ubuntu-latest + if: github.event.repository.owner.id == github.event.sender.id + env: + KS_TOKEN: ${{ secrets.KS_TOKEN }} + steps: + - name: Checkout + uses: actions/checkout@v2 + - name: Use Node.js 12.x + uses: actions/setup-node@v1 + with: + node-version: 12.x + - name: npm install + run: | + npm install + - name: 运行 【快手视频签到】 + if: env.KS_TOKEN + run: | + node Task/kuaishou.js + env: + PUSH_KEY: ${{ secrets.PUSH_KEY || github.event.client_payload.PUSH_KEY }} + BARK_PUSH: ${{ secrets.BARK_PUSH || github.event.client_payload.BARK_PUSH }} + BARK_SOUND: ${{ secrets.BARK_SOUND || github.event.client_payload.BARK_SOUND }} + TG_BOT_TOKEN: ${{ secrets.TG_BOT_TOKEN || github.event.client_payload.TG_BOT_TOKEN }} + TG_USER_ID: ${{ secrets.TG_USER_ID || github.event.client_payload.TG_USER_ID }} + DD_BOT_TOKEN: ${{ secrets.DD_BOT_TOKEN || github.event.client_payload.DD_BOT_TOKEN }} + DD_BOT_SECRET: ${{ secrets.DD_BOT_SECRET || github.event.client_payload.DD_BOT_SECRET }} + IGOT_PUSH_KEY: ${{ secrets.IGOT_PUSH_KEY || github.event.client_payload.IGOT_PUSH_KEY }} diff --git a/.github/workflows/midu_read.yml b/.github/workflows/midu_read.yml index eb2d4c9932..3b2e24c6a2 100644 --- a/.github/workflows/midu_read.yml +++ b/.github/workflows/midu_read.yml @@ -1,12 +1,12 @@ # This workflow will do a clean install of node dependencies, build the source code and run tests across different versions of node # For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions -name: midu_read +name: 米读 on: workflow_dispatch: schedule: - - cron: '*/30 1-18/2 * * *' + - cron: '*/15 1-14 * * *' jobs: build: @@ -16,11 +16,12 @@ jobs: MIDU_TIME: ${{ secrets.MIDU_TIME }} MIDU_SIGN: ${{ secrets.MIDU_SIGN }} steps: - - uses: actions/checkout@v1 - - name: Use Node.js 10.x + - name: Checkout + uses: actions/checkout@v2 + - name: Use Node.js 12.x uses: actions/setup-node@v1 with: - node-version: 10.x + node-version: 12.x - name: npm install run: | npm install diff --git a/.github/workflows/repo_sync.yml b/.github/workflows/repo_sync.yml new file mode 100644 index 0000000000..4655bfcdae --- /dev/null +++ b/.github/workflows/repo_sync.yml @@ -0,0 +1,47 @@ +# File: .github/workflows/repo-sync.yml +name: sync-Sunert-scripts +on: + schedule: + - cron: '1 0,12,22 * * *' + workflow_dispatch: + watch: + types: started + repository_dispatch: + types: sync-Sunert-scripts +jobs: + repo-sync: + env: + PAT: ${{ secrets.PAT }} #此处PAT需要申请,教程详见:https://www.jianshu.com/p/bb82b3ad1d11 + dst_key: ${{ secrets.GITEE_PRIVATE_KEY }} # 我自己同步到gitee使用,其他人可忽略 + runs-on: ubuntu-latest + if: github.event.repository.owner.id == github.event.sender.id + steps: + - uses: actions/checkout@v2 + with: + persist-credentials: false + + - name: sync Sunert-scripts + uses: repo-sync/github-sync@v2 + if: env.PAT + with: + source_repo: "https://github.com/Sunert/Scripts.git" + source_branch: "master" + destination_branch: "master" + github_token: ${{ secrets.PAT }} + # 我自己同步到gitee使用,其他人可忽略 + - name: sync github -> gitee + uses: Yikun/hub-mirror-action@master + if: env.dst_key + with: + # 必选,需要同步的Github用户(源) + src: github/Sunert + # 必选,需要同步到的Gitee的用户(目的) + dst: gitee/Sunert + # 必选,更新指定库名字 + static_list: "Scripts" + + # 必选,Gitee公钥对应的私钥,https://gitee.com/profile/sshkeys + dst_key: ${{ secrets.GITEE_PRIVATE_KEY }} + + # 必选,Gitee对应的用于创建仓库的token,https://gitee.com/profile/personal_access_tokens + dst_token: ${{ secrets.GITEE_TOKEN }} diff --git a/.github/workflows/txnews.yml b/.github/workflows/txnews.yml index d7b75802de..5776b9ab18 100644 --- a/.github/workflows/txnews.yml +++ b/.github/workflows/txnews.yml @@ -4,12 +4,12 @@ # branches: # - master -name: txnews +name: 腾讯新闻 on: workflow_dispatch: schedule: - - cron: '*/7 * * * *' + - cron: '*/30 */4 * * *' watch: types: started @@ -22,11 +22,12 @@ jobs: TXNEWS_COOKIE: ${{ secrets.TXNEWS_COOKIE }} TXNEWS_VIDEO: ${{ secrets.TXNEWS_VIDEO }} steps: - - uses: actions/checkout@v1 - - name: Use Node.js 10.x + - name: Checkout + uses: actions/checkout@v2 + - name: Use Node.js 12.x uses: actions/setup-node@v1 with: - node-version: 10.x + node-version: 12.x - name: npm install run: | npm install @@ -35,12 +36,20 @@ jobs: run: | node Task/txnews.js env: - PUSH_KEY: ${{ secrets.PUSH_KEY }} - BARK_PUSH: ${{ secrets.BARK_PUSH }} - TXNEWS_NOTIFY_CONTROL: ${{ secrets.TXNEWS_NOTIFY_CONTROL }} - TG_BOT_TOKEN: ${{ secrets.TG_BOT_TOKEN }} - TG_USER_ID: ${{ secrets.TG_USER_ID }} - BARK_SOUND: ${{ secrets.BARK_SOUND }} - DD_BOT_TOKEN: ${{ secrets.DD_BOT_TOKEN }} - DD_BOT_SECRET: ${{ secrets.DD_BOT_SECRET }} - + TZ: Asia/shanghai + PUSH_KEY: ${{ secrets.PUSH_KEY}} + BARK_PUSH: ${{ secrets.BARK_PUSH}} + BARK_SOUND: ${{ secrets.BARK_SOUND}} + TG_BOT_TOKEN: ${{ secrets.TG_BOT_TOKEN}} + TG_USER_ID: ${{ secrets.TG_USER_ID}} + DD_BOT_TOKEN: ${{ secrets.DD_BOT_TOKEN}} + DD_BOT_SECRET: ${{ secrets.DD_BOT_SECRET}} + QYWX_KEY: ${{ secrets.QYWX_KEY}} + IGOT_PUSH_KEY: ${{ secrets.IGOT_PUSH_KEY}} + QQ_SKEY: ${{ secrets.QQ_SKEY}} + QQ_MODE: ${{ secrets.QQ_MODE}} + PUSH_PLUS_TOKEN: ${{ secrets.PUSH_PLUS_TOKEN}} + PUSH_PLUS_USER: ${{ secrets.PUSH_PLUS_USER}} + TG_PROXY_HOST: ${{ secrets.TG_PROXY_HOST}} + TG_PROXY_PORT: ${{ secrets.TG_PROXY_PORT}} + \ No newline at end of file diff --git a/.github/workflows/txnews_auto.yml b/.github/workflows/txnews_auto.yml new file mode 100644 index 0000000000..8d99b92a64 --- /dev/null +++ b/.github/workflows/txnews_auto.yml @@ -0,0 +1,65 @@ + + +name: 腾讯新闻自动阅读 + +on: + workflow_dispatch: + schedule: + - cron: '*/15 */3 * * *' + watch: + types: started +jobs: + build: + runs-on: ubuntu-latest + if: github.event.repository.owner.id == github.event.sender.id + env: + TX_CK: ${{ secrets.TX_CK }} + TX_CK2: ${{ secrets.TX_CK2 }} + TX_CK3: ${{ secrets.TX_CK3 }} + TX_CK4: ${{ secrets.TX_CK4 }} + TZ: Asia/shanghai + steps: + - name: Checkout + uses: actions/checkout@v2 + - name: Use Node.js 12.x + uses: actions/setup-node@v1 + with: + node-version: 12.x + - name: npm install + run: | + npm install + - name: '运行 【腾讯新闻自动阅读账号一】' + if: env.TX_CK + run: | + node Task/txnews_task.js + env: + TX_CK: ${{ secrets.TX_CK }} + TX_READ: ${{ secrets.TX_READ }} + TX_VIDEO: ${{ secrets.TX_VIDEO }} + + - name: '运行 【腾讯新闻自动阅读账号二】' + if: env.TX_CK2 + run: | + node Task/txnews_task.js + env: + TX_CK: ${{ secrets.TX_CK2 }} + TX_READ: ${{ secrets.TX_READ2 }} + TX_VIDEO: ${{ secrets.TX_VIDEO2 }} + + - name: '运行 【腾讯新闻自动阅读账号三】' + if: env.TX_CK3 + run: | + node Task/txnews_task.js + env: + TX_CK: ${{ secrets.TX_CK3 }} + TX_READ: ${{ secrets.TX_READ3 }} + TX_VIDEO: ${{ secrets.TX_VIDEO3 }} + + - name: '运行 【腾讯新闻自动阅读账号四】' + if: env.TX_CK4 + run: | + node Task/txnews_task.js + env: + TX_CK: ${{ secrets.TX_CK4 }} + TX_READ: ${{ secrets.TX_READ4 }} + TX_VIDEO: ${{ secrets.TX_VIDEO4 }} diff --git a/.github/workflows/weibo.yml b/.github/workflows/weibo.yml index afeaabbfd7..4e0c29f365 100644 --- a/.github/workflows/weibo.yml +++ b/.github/workflows/weibo.yml @@ -1,5 +1,5 @@ -name: weibo +name: 微博每日签到打卡 on: workflow_dispatch: @@ -13,13 +13,14 @@ jobs: if: github.event.repository.owner.id == github.event.sender.id env: WB_TOKEN: ${{ secrets.WB_TOKEN }} - WB_PAY: ${{ secrets.WB_PAY }} + WB_COOKIE: ${{ secrets.WB_COOKIE }} steps: - - uses: actions/checkout@v1 - - name: Use Node.js 10.x + - name: Checkout + uses: actions/checkout@v2 + - name: Use Node.js 12.x uses: actions/setup-node@v1 with: - node-version: 10.x + node-version: 12.x - name: npm install if: env.WB_TOKEN run: | @@ -29,10 +30,18 @@ jobs: run: | node Task/weibo.js env: - PUSH_KEY: ${{ secrets.PUSH_KEY }} - BARK_PUSH: ${{ secrets.BARK_PUSH }} - TG_BOT_TOKEN: ${{ secrets.TG_BOT_TOKEN }} - TG_USER_ID: ${{ secrets.TG_USER_ID }} - BARK_SOUND: ${{ secrets.BARK_SOUND }} - DD_BOT_TOKEN: ${{ secrets.DD_BOT_TOKEN }} - DD_BOT_SECRET: ${{ secrets.DD_BOT_SECRET }} \ No newline at end of file + PUSH_KEY: ${{ secrets.PUSH_KEY}} + BARK_PUSH: ${{ secrets.BARK_PUSH}} + BARK_SOUND: ${{ secrets.BARK_SOUND}} + TG_BOT_TOKEN: ${{ secrets.TG_BOT_TOKEN}} + TG_USER_ID: ${{ secrets.TG_USER_ID}} + DD_BOT_TOKEN: ${{ secrets.DD_BOT_TOKEN}} + DD_BOT_SECRET: ${{ secrets.DD_BOT_SECRET}} + QYWX_KEY: ${{ secrets.QYWX_KEY}} + IGOT_PUSH_KEY: ${{ secrets.IGOT_PUSH_KEY}} + QQ_SKEY: ${{ secrets.QQ_SKEY}} + QQ_MODE: ${{ secrets.QQ_MODE}} + PUSH_PLUS_TOKEN: ${{ secrets.PUSH_PLUS_TOKEN}} + PUSH_PLUS_USER: ${{ secrets.PUSH_PLUS_USER}} + TG_PROXY_HOST: ${{ secrets.TG_PROXY_HOST}} + TG_PROXY_PORT: ${{ secrets.TG_PROXY_PORT}} \ No newline at end of file diff --git a/.github/workflows/youth.yml b/.github/workflows/youth.yml index f9e765a189..11837ceb43 100644 --- a/.github/workflows/youth.yml +++ b/.github/workflows/youth.yml @@ -1,12 +1,12 @@ # This workflow will do a clean install of node dependencies, build the source code and run tests across different versions of node # For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions -name: youth +name: 中青看点 on: workflow_dispatch: schedule: - - cron: '*/12 * * * *' + - cron: '*/7 */5 * * *' watch: types: started @@ -17,14 +17,14 @@ jobs: env: YOUTH_HEADER: ${{ secrets.YOUTH_HEADER }} YOUTH_ARTBODY: ${{ secrets.YOUTH_ARTBODY }} - YOUTH_REDBODY: ${{ secrets.YOUTH_REDBODY }} YOUTH_TIME: ${{ secrets.YOUTH_TIME }} steps: - - uses: actions/checkout@v1 - - name: Use Node.js 10.x + - name: Checkout + uses: actions/checkout@v2 + - name: Use Node.js 12.x uses: actions/setup-node@v1 with: - node-version: 10.x + node-version: 12.x - name: npm install if: env.YOUTH_HEADER run: | @@ -35,12 +35,21 @@ jobs: node Task/youth.js env: YOUTH_NOTIFY_CONTROL: ${{ secrets.YOUTH_NOTIFY_CONTROL }} - PUSH_KEY: ${{ secrets.PUSH_KEY }} - BARK_PUSH: ${{ secrets.BARK_PUSH }} - TG_BOT_TOKEN: ${{ secrets.TG_BOT_TOKEN }} - TG_USER_ID: ${{ secrets.TG_USER_ID }} - BARK_SOUND: ${{ secrets.BARK_SOUND }} - DD_BOT_TOKEN: ${{ secrets.DD_BOT_TOKEN }} - DD_BOT_SECRET: ${{ secrets.DD_BOT_SECRET }} + TZ: Asia/shanghai + PUSH_KEY: ${{ secrets.PUSH_KEY}} + BARK_PUSH: ${{ secrets.BARK_PUSH}} + BARK_SOUND: ${{ secrets.BARK_SOUND}} + TG_BOT_TOKEN: ${{ secrets.TG_BOT_TOKEN}} + TG_USER_ID: ${{ secrets.TG_USER_ID}} + DD_BOT_TOKEN: ${{ secrets.DD_BOT_TOKEN}} + DD_BOT_SECRET: ${{ secrets.DD_BOT_SECRET}} + QYWX_KEY: ${{ secrets.QYWX_KEY}} + IGOT_PUSH_KEY: ${{ secrets.IGOT_PUSH_KEY}} + QQ_SKEY: ${{ secrets.QQ_SKEY}} + QQ_MODE: ${{ secrets.QQ_MODE}} + PUSH_PLUS_TOKEN: ${{ secrets.PUSH_PLUS_TOKEN}} + PUSH_PLUS_USER: ${{ secrets.PUSH_PLUS_USER}} + TG_PROXY_HOST: ${{ secrets.TG_PROXY_HOST}} + TG_PROXY_PORT: ${{ secrets.TG_PROXY_PORT}} diff --git a/.github/workflows/youth_read.yml b/.github/workflows/youth_read.yml index df3dfc7ef7..4191724570 100644 --- a/.github/workflows/youth_read.yml +++ b/.github/workflows/youth_read.yml @@ -1,12 +1,12 @@ # This workflow will do a clean install of node dependencies, build the source code and run tests across different versions of node -# For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions +# 每日早9点到晚8点每2小时运行一次 -name: youth_read +name: 中青自动阅读 on: workflow_dispatch: schedule: - - cron: '6 1-12/2 * * *' + - cron: '6 1-22/5 * * *' watch: types: started jobs: @@ -18,12 +18,14 @@ jobs: YOUTH_READ2: ${{ secrets.YOUTH_READ2 }} YOUTH_READ3: ${{ secrets.YOUTH_READ3 }} YOUTH_READ4: ${{ secrets.YOUTH_READ4 }} + TZ: Asia/shanghai steps: - - uses: actions/checkout@v1 - - name: Use Node.js 10.x + - name: Checkout + uses: actions/checkout@v1 + - name: Use Node.js 12.x uses: actions/setup-node@v1 with: - node-version: 10.x + node-version: 12.x - name: npm install run: | npm install @@ -34,6 +36,7 @@ jobs: node Task/Youth_Read.js env: YOUTH_READ: ${{ secrets.YOUTH_READ }} + YOUTH_ATIME: ${{ secrets.YOUTH_ATIME }} - name: '运行 【中青看点自动阅读二】' if: env.YOUTH_READ2 @@ -41,6 +44,7 @@ jobs: node Task/Youth_Read.js env: YOUTH_READ: ${{ secrets.YOUTH_READ2 }} + YOUTH_ATIME: ${{ secrets.YOUTH_ATIME2 }} - name: '运行 【中青看点自动阅读三】' if: env.YOUTH_READ3 @@ -48,10 +52,12 @@ jobs: node Task/Youth_Read.js env: YOUTH_READ: ${{ secrets.YOUTH_READ3 }} + YOUTH_ATIME: ${{ secrets.YOUTH_ATIME3 }} - name: '运行 【中青看点自动阅读四】' if: env.YOUTH_READ4 run: | node Task/Youth_Read.js env: - YOUTH_READ: ${{ secrets.YOUTH_READ4 }} \ No newline at end of file + YOUTH_READ: ${{ secrets.YOUTH_READ4 }} + YOUTH_ATIME: ${{ secrets.YOUTH_ATIME4 }} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000..3c3629e647 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +node_modules diff --git a/LICENSE b/LICENSE index b8e7853f41..dbbe355815 100644 --- a/LICENSE +++ b/LICENSE @@ -1,72 +1,661 @@ -Copyright (c) [Year] [name of copyright holder] - [Software Name] is licensed under Mulan PSL v2. - You can use this software according to the terms and conditions of the Mulan PSL v2. - You may obtain a copy of Mulan PSL v2 at: - http://license.coscl.org.cn/MulanPSL2 - THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. - See the Mulan PSL v2 for more details. - - - Mulan Permissive Software License,Version 2 - - Mulan Permissive Software License,Version 2 (Mulan PSL v2) - January 2020 http://license.coscl.org.cn/MulanPSL2 - - Your reproduction, use, modification and distribution of the Software shall be subject to Mulan PSL v2 (this License) with the following terms and conditions: - - 0. Definition - - Software means the program and related documents which are licensed under this License and comprise all Contribution(s). - - Contribution means the copyrightable work licensed by a particular Contributor under this License. - - Contributor means the Individual or Legal Entity who licenses its copyrightable work under this License. - - Legal Entity means the entity making a Contribution and all its Affiliates. - - Affiliates means entities that control, are controlled by, or are under common control with the acting entity under this License, ‘control’ means direct or indirect ownership of at least fifty percent (50%) of the voting power, capital or other securities of controlled or commonly controlled entity. - - 1. Grant of Copyright License - - Subject to the terms and conditions of this License, each Contributor hereby grants to you a perpetual, worldwide, royalty-free, non-exclusive, irrevocable copyright license to reproduce, use, modify, or distribute its Contribution, with modification or not. - - 2. Grant of Patent License - - Subject to the terms and conditions of this License, each Contributor hereby grants to you a perpetual, worldwide, royalty-free, non-exclusive, irrevocable (except for revocation under this Section) patent license to make, have made, use, offer for sale, sell, import or otherwise transfer its Contribution, where such patent license is only limited to the patent claims owned or controlled by such Contributor now or in future which will be necessarily infringed by its Contribution alone, or by combination of the Contribution with the Software to which the Contribution was contributed. The patent license shall not apply to any modification of the Contribution, and any other combination which includes the Contribution. If you or your Affiliates directly or indirectly institute patent litigation (including a cross claim or counterclaim in a litigation) or other patent enforcement activities against any individual or entity by alleging that the Software or any Contribution in it infringes patents, then any patent license granted to you under this License for the Software shall terminate as of the date such litigation or activity is filed or taken. - - 3. No Trademark License - - No trademark license is granted to use the trade names, trademarks, service marks, or product names of Contributor, except as required to fulfill notice requirements in Section 4. - - 4. Distribution Restriction - - You may distribute the Software in any medium with or without modification, whether in source or executable forms, provided that you provide recipients with a copy of this License and retain copyright, patent, trademark and disclaimer statements in the Software. - - 5. Disclaimer of Warranty and Limitation of Liability - - THE SOFTWARE AND CONTRIBUTION IN IT ARE PROVIDED WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED. IN NO EVENT SHALL ANY CONTRIBUTOR OR COPYRIGHT HOLDER BE LIABLE TO YOU FOR ANY DAMAGES, INCLUDING, BUT NOT LIMITED TO ANY DIRECT, OR INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING FROM YOUR USE OR INABILITY TO USE THE SOFTWARE OR THE CONTRIBUTION IN IT, NO MATTER HOW IT’S CAUSED OR BASED ON WHICH LEGAL THEORY, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - - 6. Language - - THIS LICENSE IS WRITTEN IN BOTH CHINESE AND ENGLISH, AND THE CHINESE VERSION AND ENGLISH VERSION SHALL HAVE THE SAME LEGAL EFFECT. IN THE CASE OF DIVERGENCE BETWEEN THE CHINESE AND ENGLISH VERSIONS, THE CHINESE VERSION SHALL PREVAIL. - - END OF THE TERMS AND CONDITIONS - - How to Apply the Mulan Permissive Software License,Version 2 (Mulan PSL v2) to Your Software - - To apply the Mulan PSL v2 to your work, for easy identification by recipients, you are suggested to complete following three steps: - - i Fill in the blanks in following statement, including insert your software name, the year of the first publication of your software, and your name identified as the copyright owner; - - ii Create a file named “LICENSE” which contains the whole context of this License in the first directory of your software package; - - iii Attach the statement to the appropriate annotated syntax at the beginning of each source file. - - - Copyright (c) [Year] [name of copyright holder] - [Software Name] is licensed under Mulan PSL v2. - You can use this software according to the terms and conditions of the Mulan PSL v2. - You may obtain a copy of Mulan PSL v2 at: - http://license.coscl.org.cn/MulanPSL2 - THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. - See the Mulan PSL v2 for more details. + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/README.md b/README.md index 6978379365..90b08aa099 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,22 @@ -![Anurag’s github stats](https://github-readme-stats.vercel.app/api?username=Sunert&show_icons=true&theme=merko) +
+

本仓库不再维护

+ + + + + +
-# 本仓库不再维护 +
+ +[跳转到任务配置](https://github.com/Sunert/Scripts/tree/master/TaskConf) --- [跳转到脚本列表](https://github.com/Sunert/Scripts/tree/master/Task) + +*** ## 免责声明: -* 本仓库发布的Script项目中涉及的任何解锁和解密分析脚本,仅用于测试和学习研究,不能保证其合法性,准确性,完整性和有效性,请根据情况自行判断. +* 本仓库发布的Script项目中涉及的任何解锁和解密分析脚本,仅用于测试和学习研究,禁止用于商业用途,不能保证其合法性,准确性,完整性和有效性,请根据情况自行判断. * Sunert对任何脚本问题概不负责,包括但不限于由任何脚本错误导致的任何损失或损害. @@ -17,15 +28,24 @@ * 任何以任何方式查看此项目的人或直接或间接使用该Script项目的任何脚本的使用者都应仔细阅读此声明。Sunert保留随时更改或补充此免责声明的权利。一旦使用并复制了任何相关脚本或Script项目的规则,则视为您已接受此免责声明. - **您必须在下载后的24小时内从计算机或手机中完全删除以上内容.**
-> ***您使用或者复制了本仓库且本人制作的任何脚本,则视为`已接受`此免责声明,请仔细阅读*** +- 您必须在下载后的24小时内从计算机或手机中完全删除以上内容.
+
您使用或者复制了本仓库且本人制作的任何脚本,则视为 已接受 此免责声明,请仔细阅读 +
+ +*** #### 开发者不易,请赏杯茶水费 -
+
+
+--- ### 特别感谢: -* [@NobyDa](https://github.com/NobyDa) -* [@chavyleung](https://github.com/chavyleung) + * [@chavyleung](https://github.com/chavyleung) + + * [@NobyDa](https://github.com/NobyDa) + + * [@lxk0301](https://github.com/lxk0301) + * [@id77_Github](https://github.com/id77) diff --git a/Script/115lx.js b/Script/115lx.js index b70089bff4..a725412ae7 100644 --- a/Script/115lx.js +++ b/Script/115lx.js @@ -10,7 +10,6 @@ http-response ^https?:\/\/webapi\.115\.com\/user\/check_sign.*$ script-path=http ^http:\/\/115\.com\/\?ct=sign$ http://115.com/lx?taskdg=1 header 4.快速创建下载任务的快捷指令: https://www.icloud.com/shortcuts/31e3a877cec340a48192aa081e25c05e */ - var body = $response.body; if ($request.url.indexOf('/user/check_sign') != -1) { let json = JSON.parse(body); diff --git a/Script/CheckIP.js b/Script/CheckIP.js index 8b5fa427bd..06a9046b85 100644 --- a/Script/CheckIP.js +++ b/Script/CheckIP.js @@ -26,6 +26,22 @@ } } */ +function ENWORD(par) { + par = par.replace(/[\.\_\-\d]+/g," ") + let myRequest = { + url: "http://translate.google.cn/translate_a/single?client=gtx&sl=auto&tl=zh-CN&dt=t&q=" + encodeURI(par), + method: "GET" + }; +$task.fetch(myRequest).then(response => { + //console.log($response.body) + data = response.body + par = data.split(/[\"]+/g)[1]; + console.log(par); + return par; + }, reason =>{ + return par; + }) +} function ISP_ValidCheck(para) { if(para=="Microsoft Azure Cloud (eastasia)"){ return "微软云服务" @@ -77,13 +93,13 @@ return "中西部" } else if(regionName=="臺灣省 or 台灣省"){ - return city0 + return "台湾省" } else if(regionName=="Moscow"){ return "莫斯科" } else if(regionName=="新加坡"){ - return city0 + return "新加坡" } else if(regionName=="Tuen Mun"){ return "屯门" @@ -116,12 +132,24 @@ { return "东京" } + else if(regionName=="Taichung") + { + return "台中" + } else { return regionName } } function Org_ValidCheck(para) { + if(para.indexOf("Networks Limited")>-1){ + para = para.replace("Networks Limited","网络技术有限公司") + return para + } + if(para.indexOf("AWS")>-1){ + para = para.replace("AWS","亚马逊云服务") + return para + } if(para=="Microsoft Azure Cloud (eastasia)"){ return "微软云服务" } @@ -194,4 +222,4 @@ var subtitle =flags.get(obj['countryCode'])+City_ValidCheck(obj['city'])+'📀'+Org_ValidCheck(obj['org'])+'🌍'+obj['continent']; var ip = obj['query']; var description = '服务商:'+ISP_ValidCheck(obj['isp']) +'\n'+'DNS:'+ obj['reverse'] +'\n'+'地区:' +City_ValidCheck(obj['regionName'])+obj['district']+'\n' +'洲际:'+obj['continent'] +'\n'+'IP:'+obj['query'] +'\n' +'托管:'+ obj['hosting']; -$done({title, subtitle, ip, description}); \ No newline at end of file +$done({title, subtitle, ip, description}); diff --git a/Script/altstore.js b/Script/altstore.js index fa20308f64..efccde03d8 100644 --- a/Script/altstore.js +++ b/Script/altstore.js @@ -28,3 +28,4 @@ obj ={ "self":"https://www.patreon.com/api/oauth2/v2/user/30618536" } } + diff --git a/Script/xigua_ad.js b/Script/xigua_ad.js new file mode 100644 index 0000000000..8131ab9b79 --- /dev/null +++ b/Script/xigua_ad.js @@ -0,0 +1,14 @@ +/* + 西瓜视频去除内容页广告 +[rewrite_local] +https:\/\/api3-normal-c-hl\.ixigua\.com\/video\/app\/stream\/ url script-response-body xigua_ad.js +[mitm] +hostname = api*-normal-c-hl.ixigua.com +*/ + var obj = JSON.parse($response.body); + for (i=0; i< obj.data.length;i++){ + if(obj.data[i].content.indexOf("ad_label") > -1) { + delete obj.data[i].content + } + } +$done(JSON.stringify(obj)) diff --git a/Surge_Task/Sunert_Cookie.sgmodule b/Surge_Task/Sunert_Cookie.sgmodule new file mode 100644 index 0000000000..78c94f0675 --- /dev/null +++ b/Surge_Task/Sunert_Cookie.sgmodule @@ -0,0 +1,64 @@ +#!name=Task Cookie - By Sunert +#!desc=该模块适用于获取任务Cookie,仅集成Sunert签到任务Cookie。您可以在使用后手动将其禁用,以免产生不必要的MITM.。 +#!system=ios + +# GitHub主页(https://github.com/Sunert/Scripts) +# TG聊天群 (https://t.me/EveryLucky) +# 定时脚本 + +[Script] +# 定时脚本Cookie + +# 数码之家 Cookie. +数码之家 = type=http-request,pattern=https:\/\/www\.mydigit\.cn\/plugin\.php\?id=k_misign:sign&operation=qiandao,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/mydigit.js + +# 中青看点 +中青看点 = type=http-request,pattern=https:\/\/kd\.youth\.cn\/WebApi\/NewTaskIos\/getTaskList,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/youth.js + +中青看点 = type=http-request,pattern=https:\/\/ios\.baertt\.com\/v5\/article\/complete,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/youth.js, requires-body=true + +中青看点 = type=http-request,pattern=https:\/\/ios\.baertt\.com\/v5\/article\/red_packet,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/youth.js, requires-body=true + +中青看点 = type=http-request,pattern=https:\/\/ios\.baertt\.com\/v5\/user\/app_stay\.json,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/youth.js, requires-body=true + + +# 腾讯新闻 +腾讯新闻 = type=http-request,pattern=https:\/\/api\.inews\.qq\.com\/event\/v1\/user\/event\/report\?,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/txnews.js, requires-body=true + +# 新浪新闻 +新浪新闻 = type=http-request,pattern=https:\/\/newsapi\.sina\.cn\/\?resource=hbpage&newsId=HB-1-sina_gold_center,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/sinanews.js + +新浪新闻 = type=http-request,pattern=https:\/\/newsapi\.sina\.cn\/\?resource=userpoint\/signIn,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/sinanews.js + +# 新浪微博 +微博签到 = type=http-request,pattern=https:\/\/api\.weibo\.cn\/\d\/page\/\w+\?gsid,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/weibo.js + +# 微博钱包签到 +钱包签到 = type=http-request,pattern=https:\/\/pay\.sc\.weibo\.com\/aj\/mobile\/home\/welfare\/signin\/do\?,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/weibo.js + +# 快手极速版 +快手极速版 = type=http-request,pattern=https:\/\/nebula\.kuaishou\.com\/nebula\/task\/earning\?,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/kuaishou.js + +# 来客有礼 +来客有礼 = type=http-request,pattern=https:\/\/draw\.jdfcloud\.com\/\/api\/bean\/square\/silverBean\/task\/get\?,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/lkyl.js + +# 电视家 +电视家签到 = type=http-request,pattern=http:\/\/act\.gaoqingdianshi\.com\/\/api\/v4\/sign\/signin,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/dianshijia.js + +电视家兑换 = type=http-request,pattern=http:\/\/api\.gaoqingdianshi\.com\/api\/v2\/cash\/withdrawal,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/dianshijia.js + +# 电信套餐查询 +电信套餐查询 = script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/telecomInfinity.js,type=http-request,pattern=https?:\/\/e\.189\.cn\/store\/user\/package_detail\.do + +# 聚看点 +中青看点 = type=https:\/\/www\.xiaodouzhuan\.cn\/jkd\/newMobileMenu\/infoMe\.action,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/jukan.js, requires-body=true + + +[MITM] +hostname = %APPEND% www.mydigit.cn, kd.youth.cn, ios.baertt.com, api.inews.qq.com, newsapi.sina.cn, api.weibo.cn, pay.sc.weibo.com, nebula.kuaishou.com, draw.jdfcloud.com, e.189.cn, www.xiaodouzhuan.cn + + + + + + diff --git a/Surge_Task/Sunert_Task.sgmodule b/Surge_Task/Sunert_Task.sgmodule new file mode 100644 index 0000000000..2ea3b4d4d5 --- /dev/null +++ b/Surge_Task/Sunert_Task.sgmodule @@ -0,0 +1,59 @@ +#!name=Task - By Sunert +#!desc=该模块适用于定时签到:集成Sunert签到脚本。建议本地安装以便自定义修改签到时间。 +#!system=ios + +# GitHub主页(https://github.com/Sunert/Scripts) +# TG聊天群 (https://t.me/EveryLucky) +# 定时脚本 + +[Script] +# 定时脚本 + +# > 电视节目预告 +电视节目预告 = type=cron,cronexp=0 0 8 * * *,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/tvpreview.js,script-update-interval=0 + +# > 12306余票及列车时刻表查询 +12306 = type=cron,cronexp=0 0 8 * * *,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/trainquery.js + +# > 实时货币换算 +实时汇率 = type=cron,cronexp=35 5 0 * * *,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/exchangeRate.js,script-update-interval=0 + +# > 中国电信套餐 +中国电信套餐 = type=cron,cronexp=50 4 0 * * *,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/telecomInfinity.js,script-update-interval=0 + +# > 腾讯新闻 +腾讯新闻 = type=cron,cronexp=35 */7 */2 * * *,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/txnews.js,script-update-interval=0 + +# > 京东到家 +京东到家 = type=cron,cronexp=25 5 0 * * *,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/jddj.js,script-update-interval=0 + +# > 微信小程序-来客有礼 +# 来客有礼 = type=cron,cronexp=30 5 0 * * *,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/lkyl.js,script-update-interval=0 + +# > 电视家 +电视家 = type=cron,cronexp=0 0 7,12,22 * * *,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/dianshijia.js,script-update-interval=0 + +# > 快手极速版 +快手极速版 = type=cron,cronexp=40 5 0 * * *,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/kuaishou.js,script-update-interval=0 + +# > 微博签到 & 微博钱包 +微博(钱包) = type=cron,cronexp=35 2 0 * * *,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/weibo.js,script-update-interval=0 + +# > 新浪新闻 +新浪新闻 = type=cron,cronexp=0 5 0 * * *,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/sinanews.js + +# > 中青看点极速版 +中青看点极速版 = type=cron,cronexp=35 */5 */3 * * *,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/youth.js,script-update-interval=0 + +# > 数码之家 +数码之家 = type=cron,cronexp=0 7 0 * * *,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/mydigit.js,script-update-interval=0 + +# > 聚看点 +聚看点 = type=cron,cronexp=0 */30 * * * *,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/jukan.js,script-update-interval=0 + +# > 谷歌翻译 +谷歌翻译 = type=cron,cronexp=0 5 10 * * *,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/translate.js,script-update-interval=0 + +# > 墨迹天气 +墨迹天气 = type=cron,cronexp=0 5 10 * * *,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/moji.js,script-update-interval=0 + diff --git a/Task/Env.js b/Task/Env.js index ee7e7d8197..f98a0a88c4 100644 --- a/Task/Env.js +++ b/Task/Env.js @@ -3,61 +3,52 @@ function Env(name, opts) { constructor(env) { this.env = env } - send(opts, method = 'GET') { - opts = typeof opts === 'string' ? { url: opts } : opts - let sender = this.get + opts = typeof opts === 'string' ? { url: opts } : opts; + let sender = this.get; if (method === 'POST') { sender = this.post } return new Promise((resolve, reject) => { sender.call(this, opts, (err, resp, body) => { - if (err) reject(err) + if (err) reject(err); else resolve(resp) }) }) } - get(opts) { return this.send.call(this.env, opts) } - post(opts) { return this.send.call(this.env, opts, 'POST') } } - return new (class { constructor(name, opts) { - this.name = name - this.http = new Http(this) - this.data = null - this.dataFile = 'box.dat' - this.logs = [] - this.isMute = false - this.isNeedRewrite = false + this.name = name, + this.http = new Http(this), + this.data = null, + this.dataFile = 'box.dat', + this.logs = [], + this.isMute = false, + this.isNeedRewrite = false, this.logSeparator = '\n' - this.startTime = new Date().getTime() - Object.assign(this, opts) + this.startTime = new Date().getTime(); + Object.assign(this, opts); this.log('', `🔔${this.name}, 开始!`) } - isNode() { return 'undefined' !== typeof module && !!module.exports } - isQuanX() { return 'undefined' !== typeof $task } - isSurge() { return 'undefined' !== typeof $httpClient && 'undefined' === typeof $loon } - isLoon() { return 'undefined' !== typeof $loon } - toObj(str, defaultValue = null) { try { return JSON.parse(str) @@ -65,7 +56,6 @@ function Env(name, opts) { return defaultValue } } - toStr(obj, defaultValue = null) { try { return JSON.stringify(obj) @@ -73,10 +63,9 @@ function Env(name, opts) { return defaultValue } } - getjson(key, defaultValue) { - let json = defaultValue - const val = this.getdata(key) + let json = defaultValue; + const val = this.getdata(key); if (val) { try { json = JSON.parse(this.getdata(key)) @@ -84,7 +73,6 @@ function Env(name, opts) { } return json } - setjson(val, key) { try { return this.setdata(JSON.stringify(val), key) @@ -92,21 +80,19 @@ function Env(name, opts) { return false } } - getScript(url) { return new Promise((resolve) => { this.get({ url }, (err, resp, body) => resolve(body)) }) } - runScript(script, runOpts) { return new Promise((resolve) => { - let httpapi = this.getdata('@chavy_boxjs_userCfgs.httpapi') - httpapi = httpapi ? httpapi.replace(/\n/g, '').trim() : httpapi - let httpapi_timeout = this.getdata('@chavy_boxjs_userCfgs.httpapi_timeout') - httpapi_timeout = httpapi_timeout ? httpapi_timeout * 1 : 20 - httpapi_timeout = runOpts && runOpts.timeout ? runOpts.timeout : httpapi_timeout - const [key, addr] = httpapi.split('@') + let httpapi = this.getdata('@chavy_boxjs_userCfgs.httpapi'); + httpapi = httpapi ? httpapi.replace(/\n/g, '').trim() : httpapi; + let httpapi_timeout = this.getdata('@chavy_boxjs_userCfgs.httpapi_timeout'); + httpapi_timeout = httpapi_timeout ? httpapi_timeout * 1 : 20; + httpapi_timeout = runOpts && runOpts.timeout ? runOpts.timeout : httpapi_timeout; + const [key, addr] = httpapi.split('@'); const opts = { url: `http://${addr}/v1/scripting/evaluate`, body: { script_text: script, mock_type: 'cron', timeout: httpapi_timeout }, @@ -118,14 +104,14 @@ function Env(name, opts) { loaddata() { if (this.isNode()) { - this.fs = this.fs ? this.fs : require('fs') - this.path = this.path ? this.path : require('path') - const curDirDataFilePath = this.path.resolve(this.dataFile) - const rootDirDataFilePath = this.path.resolve(process.cwd(), this.dataFile) - const isCurDirDataFile = this.fs.existsSync(curDirDataFilePath) - const isRootDirDataFile = !isCurDirDataFile && this.fs.existsSync(rootDirDataFilePath) + this.fs = this.fs ? this.fs : require('fs'); + this.path = this.path ? this.path : require('path'); + const curDirDataFilePath = this.path.resolve(this.dataFile); + const rootDirDataFilePath = this.path.resolve(process.cwd(), this.dataFile); + const isCurDirDataFile = this.fs.existsSync(curDirDataFilePath); + const isRootDirDataFile = !isCurDirDataFile && this.fs.existsSync(rootDirDataFilePath); if (isCurDirDataFile || isRootDirDataFile) { - const datPath = isCurDirDataFile ? curDirDataFilePath : rootDirDataFilePath + const datPath = isCurDirDataFile ? curDirDataFilePath : rootDirDataFilePath; try { return JSON.parse(this.fs.readFileSync(datPath)) } catch (e) { @@ -134,16 +120,15 @@ function Env(name, opts) { } else return {} } else return {} } - writedata() { if (this.isNode()) { - this.fs = this.fs ? this.fs : require('fs') - this.path = this.path ? this.path : require('path') - const curDirDataFilePath = this.path.resolve(this.dataFile) - const rootDirDataFilePath = this.path.resolve(process.cwd(), this.dataFile) - const isCurDirDataFile = this.fs.existsSync(curDirDataFilePath) - const isRootDirDataFile = !isCurDirDataFile && this.fs.existsSync(rootDirDataFilePath) - const jsondata = JSON.stringify(this.data) + this.fs = this.fs ? this.fs : require('fs'); + this.path = this.path ? this.path : require('path'); + const curDirDataFilePath = this.path.resolve(this.dataFile); + const rootDirDataFilePath = this.path.resolve(process.cwd(), this.dataFile); + const isCurDirDataFile = this.fs.existsSync(curDirDataFilePath); + const isRootDirDataFile = !isCurDirDataFile && this.fs.existsSync(rootDirDataFilePath); + const jsondata = JSON.stringify(this.data); if (isCurDirDataFile) { this.fs.writeFileSync(curDirDataFilePath, jsondata) } else if (isRootDirDataFile) { @@ -153,22 +138,20 @@ function Env(name, opts) { } } } - lodash_get(source, path, defaultValue = undefined) { const paths = path.replace(/\[(\d+)\]/g, '.$1').split('.') - let result = source + let result = source; for (const p of paths) { - result = Object(result)[p] + result = Object(result)[p]; if (result === undefined) { return defaultValue } } return result } - lodash_set(obj, path, value) { - if (Object(obj) !== obj) return obj - if (!Array.isArray(path)) path = path.toString().match(/[^.[\]]+/g) || [] + if (Object(obj) !== obj) return obj; + if (!Array.isArray(path)) path = path.toString().match(/[^.[\]]+/g) || []; path .slice(0, -1) .reduce((a, c, i) => (Object(a[c]) === a[c] ? a[c] : (a[c] = Math.abs(path[i + 1]) >> 0 === +path[i + 1] ? [] : {})), obj)[ @@ -176,16 +159,14 @@ function Env(name, opts) { ] = value return obj } - getdata(key) { - let val = this.getval(key) - // 如果以 @ + let val = this.getval(key); if (/^@/.test(key)) { - const [, objkey, paths] = /^@(.*?)\.(.*?)$/.exec(key) - const objval = objkey ? this.getval(objkey) : '' + const [, objkey, paths] = /^@(.*?)\.(.*?)$/.exec(key); + const objval = objkey ? this.getval(objkey) : ''; if (objval) { try { - const objedval = JSON.parse(objval) + const objedval = JSON.parse(objval); val = objedval ? this.lodash_get(objedval, paths, '') : val } catch (e) { val = '' @@ -194,20 +175,19 @@ function Env(name, opts) { } return val } - setdata(val, key) { - let issuc = false + let issuc = false; if (/^@/.test(key)) { - const [, objkey, paths] = /^@(.*?)\.(.*?)$/.exec(key) - const objdat = this.getval(objkey) - const objval = objkey ? (objdat === 'null' ? null : objdat || '{}') : '{}' + const [, objkey, paths] = /^@(.*?)\.(.*?)$/.exec(key); + const objdat = this.getval(objkey); + const objval = objkey ? (objdat === 'null' ? null : objdat || '{}') : '{}'; try { - const objedval = JSON.parse(objval) - this.lodash_set(objedval, paths, val) + const objedval = JSON.parse(objval); + this.lodash_set(objedval, paths, val); issuc = this.setval(JSON.stringify(objedval), objkey) } catch (e) { - const objedval = {} - this.lodash_set(objedval, paths, val) + const objedval = {}; + this.lodash_set(objedval, paths, val); issuc = this.setval(JSON.stringify(objedval), objkey) } } else { @@ -222,22 +202,21 @@ function Env(name, opts) { } else if (this.isQuanX()) { return $prefs.valueForKey(key) } else if (this.isNode()) { - this.data = this.loaddata() + this.data = this.loaddata(); return this.data[key] } else { return (this.data && this.data[key]) || null } } - setval(val, key) { if (this.isSurge() || this.isLoon()) { return $persistentStore.write(val, key) } else if (this.isQuanX()) { return $prefs.setValueForKey(val, key) } else if (this.isNode()) { - this.data = this.loaddata() - this.data[key] = val - this.writedata() + this.data = this.loaddata(), + this.data[key] = val, + this.writedata(); return true } else { return (this.data && this.data[key]) || null @@ -245,147 +224,166 @@ function Env(name, opts) { } initGotEnv(opts) { - this.got = this.got ? this.got : require('got') - this.cktough = this.cktough ? this.cktough : require('tough-cookie') - this.ckjar = this.ckjar ? this.ckjar : new this.cktough.CookieJar() + this.got = this.got ? this.got : require('got'); + this.cktough = this.cktough ? this.cktough : require('tough-cookie'); + this.ckjar = this.ckjar ? this.ckjar : new this.cktough.CookieJar(); if (opts) { - opts.headers = opts.headers ? opts.headers : {} + opts.headers = opts.headers ? opts.headers : {}; if (undefined === opts.headers.Cookie && undefined === opts.cookieJar) { opts.cookieJar = this.ckjar } } } - get(opts, callback = () => {}) { if (opts.headers) { - delete opts.headers['Content-Type'] + delete opts.headers['Content-Type']; delete opts.headers['Content-Length'] } if (this.isSurge() || this.isLoon()) { if (this.isSurge() && this.isNeedRewrite) { - opts.headers = opts.headers || {} + opts.headers = opts.headers || {}; Object.assign(opts.headers, { 'X-Surge-Skip-Scripting': false }) } $httpClient.get(opts, (err, resp, body) => { if (!err && resp) { - resp.body = body + resp.body = body, resp.statusCode = resp.status } callback(err, resp, body) }) } else if (this.isQuanX()) { if (this.isNeedRewrite) { - opts.opts = opts.opts || {} + opts.opts = opts.opts || {}; Object.assign(opts.opts, { hints: false }) } $task.fetch(opts).then( (resp) => { - const { statusCode: status, statusCode, headers, body } = resp + const { statusCode: status, statusCode, headers, body } = resp; callback(null, { status, statusCode, headers, body }, body) }, (err) => callback(err) ) } else if (this.isNode()) { - this.initGotEnv(opts) + this.initGotEnv(opts); this.got(opts) .on('redirect', (resp, nextOpts) => { try { if (resp.headers['set-cookie']) { - const ck = resp.headers['set-cookie'].map(this.cktough.Cookie.parse).toString() - this.ckjar.setCookieSync(ck, null) + const ck = resp.headers['set-cookie'].map(this.cktough.Cookie.parse).toString(); + if (ck) { + this.ckjar.setCookieSync(ck, null) + } nextOpts.cookieJar = this.ckjar } } catch (e) { this.logErr(e) } - // this.ckjar.setCookieSync(resp.headers['set-cookie'].map(Cookie.parse).toString()) }) .then( (resp) => { - const { statusCode: status, statusCode, headers, body } = resp + const { statusCode: status, statusCode, headers, body } = resp; callback(null, { status, statusCode, headers, body }, body) }, (err) => { - const { message: error, response: resp } = err + const { message: error, response: resp } = err; callback(error, resp, resp && resp.body) } ) } } - post(opts, callback = () => {}) { - // 如果指定了请求体, 但没指定`Content-Type`, 则自动生成 if (opts.body && opts.headers && !opts.headers['Content-Type']) { opts.headers['Content-Type'] = 'application/x-www-form-urlencoded' } if (opts.headers) delete opts.headers['Content-Length'] if (this.isSurge() || this.isLoon()) { if (this.isSurge() && this.isNeedRewrite) { - opts.headers = opts.headers || {} + opts.headers = opts.headers || {}; Object.assign(opts.headers, { 'X-Surge-Skip-Scripting': false }) } $httpClient.post(opts, (err, resp, body) => { if (!err && resp) { - resp.body = body + resp.body = body, resp.statusCode = resp.status } callback(err, resp, body) }) } else if (this.isQuanX()) { - opts.method = 'POST' + opts.method = 'POST'; if (this.isNeedRewrite) { - opts.opts = opts.opts || {} + opts.opts = opts.opts || {}; Object.assign(opts.opts, { hints: false }) } $task.fetch(opts).then( (resp) => { - const { statusCode: status, statusCode, headers, body } = resp + const { statusCode: status, statusCode, headers, body } = resp; callback(null, { status, statusCode, headers, body }, body) }, (err) => callback(err) ) } else if (this.isNode()) { - this.initGotEnv(opts) - const { url, ..._opts } = opts + this.initGotEnv(opts); + const { url, ..._opts } = opts; this.got.post(url, _opts).then( (resp) => { - const { statusCode: status, statusCode, headers, body } = resp + const { statusCode: status, statusCode, headers, body } = resp; callback(null, { status, statusCode, headers, body }, body) }, (err) => { - const { message: error, response: resp } = err + const { message: error, response: resp } = err; callback(error, resp, resp && resp.body) } ) } - } - /** - * - * 示例:$.time('yyyy-MM-dd qq HH:mm:ss.S') - * :$.time('yyyyMMddHHmmssS') - * y:年 M:月 d:日 q:季 H:时 m:分 s:秒 S:毫秒 - * 其中y可选0-4位占位符、S可选0-1位占位符,其余可选0-2位占位符 - * @param {*} fmt 格式化参数 - * - */ - time(fmt) { - let o = { - 'M+': new Date().getMonth() + 1, - 'd+': new Date().getDate(), - 'H+': new Date().getHours(), - 'm+': new Date().getMinutes(), - 's+': new Date().getSeconds(), - 'q+': Math.floor((new Date().getMonth() + 3) / 3), - 'S': new Date().getMilliseconds() - } - if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (new Date().getFullYear() + '').substr(4 - RegExp.$1.length)) - for (let k in o) - if (new RegExp('(' + k + ')').test(fmt)) - fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length)) - return fmt - } - - /** + } + +/** + * 对Date的扩展,将 Date 转化为指定格式的String + * 月(M)、日(d)、12小时(h)、24小时(H)、分(m)、秒(s)、周(E)、季度(q) 可以用 1-2 个占位符 + * 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字) + * eg: + * $.time("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423 + * $.time("yyyy-MM-dd E HH:mm:ss") ==> 2009-03-10 二 20:09:04 + * $.time("yyyy-MM-dd EE hh:mm:ss") ==> 2009-03-10 周二 08:09:04 + * $.time("yyyy-MM-dd EEE hh:mm:ss") ==> 2009-03-10 星期二 08:09:04 + * $.time("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18 + * $.time("yyyy/MM/dd HH:mm", 1613568620000) ==> 2021/02/17 21:30 + */ + time(fmt, ts = null) { + const date = ts ? new Date(ts) : new Date(); + var o = { + "M+" : date.getMonth()+1, //月份 + "d+" : date.getDate(), //日 + "h" : date.getHours()%12 == 0 ? 12 : date.getHours()/12 < 1 ? "上午" + date.getHours()%12 : "下午"+ date.getHours()%12 , //小时 + "H+" : date.getHours(), //小时 + "m+" : date.getMinutes(), //分 + "s+" : date.getSeconds(), //秒 + "q+" : Math.floor((date.getMonth()+3)/3), //季度 + "S" : date.getMilliseconds() //毫秒 + }; + var week = { + "0" : "\u65e5", + "1" : "\u4e00", + "2" : "\u4e8c", + "3" : "\u4e09", + "4" : "\u56db", + "5" : "\u4e94", + "6" : "\u516d" + }; + if(/(y+)/.test(fmt)){ + fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length)) + } + if(/(E+)/.test(fmt)){ + fmt=fmt.replace(RegExp.$1, ((RegExp.$1.length>1) ? (RegExp.$1.length>2 ? "\u661f\u671f" : "\u5468") : "")+week[date.getDay()+""]) + } + for(var k in o){ + if(new RegExp("("+ k +")").test(fmt)){ + fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length))) + } + } + return fmt + } + /** * 系统通知 * * > 通知参数: 同时支持 QuanX 和 Loon 两种格式, EnvJs根据运行环境自动转换, Surge 环境不支持多媒体通知 @@ -401,9 +399,10 @@ function Env(name, opts) { * @param {*} opts 通知参数 * */ + msg(title = name, subt = '', desc = '', opts) { const toEnvOpts = (rawopts) => { - if (!rawopts) return rawopts + if (!rawopts) return rawopts; if (typeof rawopts === 'string') { if (this.isLoon()) return rawopts else if (this.isQuanX()) return { 'open-url': rawopts } @@ -411,12 +410,12 @@ function Env(name, opts) { else return undefined } else if (typeof rawopts === 'object') { if (this.isLoon()) { - let openUrl = rawopts.openUrl || rawopts.url || rawopts['open-url'] - let mediaUrl = rawopts.mediaUrl || rawopts['media-url'] + let openUrl = rawopts.openUrl || rawopts.url || rawopts['open-url']; + let mediaUrl = rawopts.mediaUrl || rawopts['media-url']; return { openUrl, mediaUrl } } else if (this.isQuanX()) { - let openUrl = rawopts['open-url'] || rawopts.url || rawopts.openUrl - let mediaUrl = rawopts['media-url'] || rawopts.mediaUrl + let openUrl = rawopts['open-url'] || rawopts.url || rawopts.openUrl; + let mediaUrl = rawopts['media-url'] || rawopts.mediaUrl; return { 'open-url': openUrl, 'media-url': mediaUrl } } else if (this.isSurge()) { let openUrl = rawopts.url || rawopts.openUrl || rawopts['open-url'] @@ -433,21 +432,21 @@ function Env(name, opts) { $notify(title, subt, desc, toEnvOpts(opts)) } } - let logs = ['', '==============📣系统通知📣=============='] - logs.push(title) - subt ? logs.push(subt) : '' - desc ? logs.push(desc) : '' - console.log(logs.join('\n')) - this.logs = this.logs.concat(logs) + if (!this.isMuteLog) { + let logs = ['', '==============📣系统通知📣=============='] + logs.push(title) + subt ? logs.push(subt) : ''; + desc ? logs.push(desc) : ''; + console.log(logs.join('\n')); + this.logs = this.logs.concat(logs) + } } - log(...logs) { if (logs.length > 0) { this.logs = [...this.logs, ...logs] } - console.log(logs.join(this.logSeparator)) + console.log(logs.join(this.logSeparator)) } - logErr(err, msg) { const isPrintSack = !this.isSurge() && !this.isQuanX() && !this.isLoon() if (!isPrintSack) { @@ -456,16 +455,14 @@ function Env(name, opts) { this.log('', `❗️${this.name}, 错误!`, err.stack) } } - wait(time) { return new Promise((resolve) => setTimeout(resolve, time)) } - done(val = {}) { - const endTime = new Date().getTime() - const costTime = (endTime - this.startTime) / 1000 - this.log('', `🔔${this.name}, 结束! 🕛 ${costTime} 秒`) - this.log() + const endTime = new Date().getTime(); + const costTime = (endTime - this.startTime) / 1000; + this.log('', `🔔${this.name}, 结束! 🕛 ${costTime} 秒`); + this.log(); if (this.isSurge() || this.isQuanX() || this.isLoon()) { $done(val) } diff --git a/Task/Env.min.js b/Task/Env.min.js index 5ddd120b1f..b7936f2ac8 100644 --- a/Task/Env.min.js +++ b/Task/Env.min.js @@ -1 +1 @@ -function Env(t,e){class s{constructor(t){this.env=t}send(t,e="GET"){t="string"==typeof t?{url:t}:t;let s=this.get;return"POST"===e&&(s=this.post),new Promise((e,i)=>{s.call(this,t,(t,s,r)=>{t?i(t):e(s)})})}get(t){return this.send.call(this.env,t)}post(t){return this.send.call(this.env,t,"POST")}}return new class{constructor(t,e){this.name=t,this.http=new s(this),this.data=null,this.dataFile="box.dat",this.logs=[],this.isMute=!1,this.isNeedRewrite=!1,this.logSeparator="\n",this.startTime=(new Date).getTime(),Object.assign(this,e),this.log("",`\ud83d\udd14${this.name}, \u5f00\u59cb!`)}isNode(){return"undefined"!=typeof module&&!!module.exports}isQuanX(){return"undefined"!=typeof $task}isSurge(){return"undefined"!=typeof $httpClient&&"undefined"==typeof $loon}isLoon(){return"undefined"!=typeof $loon}toObj(t,e=null){try{return JSON.parse(t)}catch{return e}}toStr(t,e=null){try{return JSON.stringify(t)}catch{return e}}getjson(t,e){let s=e;const i=this.getdata(t);if(i)try{s=JSON.parse(this.getdata(t))}catch{}return s}setjson(t,e){try{return this.setdata(JSON.stringify(t),e)}catch{return!1}}getScript(t){return new Promise(e=>{this.get({url:t},(t,s,i)=>e(i))})}runScript(t,e){return new Promise(s=>{let i=this.getdata("@chavy_boxjs_userCfgs.httpapi");i=i?i.replace(/\n/g,"").trim():i;let r=this.getdata("@chavy_boxjs_userCfgs.httpapi_timeout");r=r?1*r:20,r=e&&e.timeout?e.timeout:r;const[o,h]=i.split("@"),a={url:`http://${h}/v1/scripting/evaluate`,body:{script_text:t,mock_type:"cron",timeout:r},headers:{"X-Key":o,Accept:"*/*"}};this.post(a,(t,e,i)=>s(i))}).catch(t=>this.logErr(t))}loaddata(){if(!this.isNode())return{};{this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(this.dataFile),e=this.path.resolve(process.cwd(),this.dataFile),s=this.fs.existsSync(t),i=!s&&this.fs.existsSync(e);if(!s&&!i)return{};{const i=s?t:e;try{return JSON.parse(this.fs.readFileSync(i))}catch(t){return{}}}}}writedata(){if(this.isNode()){this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(this.dataFile),e=this.path.resolve(process.cwd(),this.dataFile),s=this.fs.existsSync(t),i=!s&&this.fs.existsSync(e),r=JSON.stringify(this.data);s?this.fs.writeFileSync(t,r):i?this.fs.writeFileSync(e,r):this.fs.writeFileSync(t,r)}}lodash_get(t,e,s){const i=e.replace(/\[(\d+)\]/g,".$1").split(".");let r=t;for(const t of i)if(r=Object(r)[t],void 0===r)return s;return r}lodash_set(t,e,s){return Object(t)!==t?t:(Array.isArray(e)||(e=e.toString().match(/[^.[\]]+/g)||[]),e.slice(0,-1).reduce((t,s,i)=>Object(t[s])===t[s]?t[s]:t[s]=Math.abs(e[i+1])>>0==+e[i+1]?[]:{},t)[e[e.length-1]]=s,t)}getdata(t){let e=this.getval(t);if(/^@/.test(t)){const[,s,i]=/^@(.*?)\.(.*?)$/.exec(t),r=s?this.getval(s):"";if(r)try{const t=JSON.parse(r);e=t?this.lodash_get(t,i,""):e}catch(t){e=""}}return e}setdata(t,e){let s=!1;if(/^@/.test(e)){const[,i,r]=/^@(.*?)\.(.*?)$/.exec(e),o=this.getval(i),h=i?"null"===o?null:o||"{}":"{}";try{const e=JSON.parse(h);this.lodash_set(e,r,t),s=this.setval(JSON.stringify(e),i)}catch(e){const o={};this.lodash_set(o,r,t),s=this.setval(JSON.stringify(o),i)}}else s=this.setval(t,e);return s}getval(t){return this.isSurge()||this.isLoon()?$persistentStore.read(t):this.isQuanX()?$prefs.valueForKey(t):this.isNode()?(this.data=this.loaddata(),this.data[t]):this.data&&this.data[t]||null}setval(t,e){return this.isSurge()||this.isLoon()?$persistentStore.write(t,e):this.isQuanX()?$prefs.setValueForKey(t,e):this.isNode()?(this.data=this.loaddata(),this.data[e]=t,this.writedata(),!0):this.data&&this.data[e]||null}initGotEnv(t){this.got=this.got?this.got:require("got"),this.cktough=this.cktough?this.cktough:require("tough-cookie"),this.ckjar=this.ckjar?this.ckjar:new this.cktough.CookieJar,t&&(t.headers=t.headers?t.headers:{},void 0===t.headers.Cookie&&void 0===t.cookieJar&&(t.cookieJar=this.ckjar))}get(t,e=(()=>{})){t.headers&&(delete t.headers["Content-Type"],delete t.headers["Content-Length"]),this.isSurge()||this.isLoon()?(this.isSurge()&&this.isNeedRewrite&&(t.headers=t.headers||{},Object.assign(t.headers,{"X-Surge-Skip-Scripting":!1})),$httpClient.get(t,(t,s,i)=>{!t&&s&&(s.body=i,s.statusCode=s.status),e(t,s,i)})):this.isQuanX()?(this.isNeedRewrite&&(t.opts=t.opts||{},Object.assign(t.opts,{hints:!1})),$task.fetch(t).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>e(t))):this.isNode()&&(this.initGotEnv(t),this.got(t).on("redirect",(t,e)=>{try{if(t.headers["set-cookie"]){const s=t.headers["set-cookie"].map(this.cktough.Cookie.parse).toString();this.ckjar.setCookieSync(s,null),e.cookieJar=this.ckjar}}catch(t){this.logErr(t)}}).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>{const{message:s,response:i}=t;e(s,i,i&&i.body)}))}post(t,e=(()=>{})){if(t.body&&t.headers&&!t.headers["Content-Type"]&&(t.headers["Content-Type"]="application/x-www-form-urlencoded"),t.headers&&delete t.headers["Content-Length"],this.isSurge()||this.isLoon())this.isSurge()&&this.isNeedRewrite&&(t.headers=t.headers||{},Object.assign(t.headers,{"X-Surge-Skip-Scripting":!1})),$httpClient.post(t,(t,s,i)=>{!t&&s&&(s.body=i,s.statusCode=s.status),e(t,s,i)});else if(this.isQuanX())t.method="POST",this.isNeedRewrite&&(t.opts=t.opts||{},Object.assign(t.opts,{hints:!1})),$task.fetch(t).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>e(t));else if(this.isNode()){this.initGotEnv(t);const{url:s,...i}=t;this.got.post(s,i).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>{const{message:s,response:i}=t;e(s,i,i&&i.body)})}}time(t){let e={"M+":(new Date).getMonth()+1,"d+":(new Date).getDate(),"H+":(new Date).getHours(),"m+":(new Date).getMinutes(),"s+":(new Date).getSeconds(),"q+":Math.floor(((new Date).getMonth()+3)/3),S:(new Date).getMilliseconds()};/(y+)/.test(t)&&(t=t.replace(RegExp.$1,((new Date).getFullYear()+"").substr(4-RegExp.$1.length)));for(let s in e)new RegExp("("+s+")").test(t)&&(t=t.replace(RegExp.$1,1==RegExp.$1.length?e[s]:("00"+e[s]).substr((""+e[s]).length)));return t}msg(e=t,s="",i="",r){const o=t=>{if(!t)return t;if("string"==typeof t)return this.isLoon()?t:this.isQuanX()?{"open-url":t}:this.isSurge()?{url:t}:void 0;if("object"==typeof t){if(this.isLoon()){let e=t.openUrl||t.url||t["open-url"],s=t.mediaUrl||t["media-url"];return{openUrl:e,mediaUrl:s}}if(this.isQuanX()){let e=t["open-url"]||t.url||t.openUrl,s=t["media-url"]||t.mediaUrl;return{"open-url":e,"media-url":s}}if(this.isSurge()){let e=t.url||t.openUrl||t["open-url"];return{url:e}}}};this.isMute||(this.isSurge()||this.isLoon()?$notification.post(e,s,i,o(r)):this.isQuanX()&&$notify(e,s,i,o(r)));let h=["","==============\ud83d\udce3\u7cfb\u7edf\u901a\u77e5\ud83d\udce3=============="];h.push(e),s&&h.push(s),i&&h.push(i),console.log(h.join("\n")),this.logs=this.logs.concat(h)}log(...t){t.length>0&&(this.logs=[...this.logs,...t]),console.log(t.join(this.logSeparator))}logErr(t,e){const s=!this.isSurge()&&!this.isQuanX()&&!this.isLoon();s?this.log("",`\u2757\ufe0f${this.name}, \u9519\u8bef!`,t.stack):this.log("",`\u2757\ufe0f${this.name}, \u9519\u8bef!`,t)}wait(t){return new Promise(e=>setTimeout(e,t))}done(t={}){const e=(new Date).getTime(),s=(e-this.startTime)/1e3;this.log("",`\ud83d\udd14${this.name}, \u7ed3\u675f! \ud83d\udd5b ${s} \u79d2`),this.log(),(this.isSurge()||this.isQuanX()||this.isLoon())&&$done(t)}}(t,e)} \ No newline at end of file +function Env(name,opts){class Http{constructor(env){this.env=env};send(opts,method='GET'){opts=typeof opts==='string'?{url:opts}:opts;let sender=this.get;if(method==='POST'){sender=this.post};return new Promise((resolve,reject)=>{sender.call(this,opts,(err,resp,body)=>{if(err)reject(err);else resolve(resp)})})};get(opts){return this.send.call(this.env,opts)};post(opts){return this.send.call(this.env,opts,'POST')}};return new(class{constructor(name,opts){this.name=name,this.http=new Http(this),this.data=null,this.dataFile='box.dat',this.logs=[],this.isMute=false,this.isNeedRewrite=false,this.logSeparator='\n';this.startTime=new Date().getTime();Object.assign(this,opts);this.log('',`🔔${this.name}, 开始!`)};isNode(){return'undefined'!==typeof module&&!!module.exports};isQuanX(){return'undefined'!==typeof $task};isSurge(){return'undefined'!==typeof $httpClient&&'undefined'===typeof $loon};isLoon(){return'undefined'!==typeof $loon};toObj(str,defaultValue=null){try{return JSON.parse(str)}catch{return defaultValue}};toStr(obj,defaultValue=null){try{return JSON.stringify(obj)}catch{return defaultValue}};getjson(key,defaultValue){let json=defaultValue;const val=this.getdata(key);if(val){try{json=JSON.parse(this.getdata(key))}catch{}};return json};setjson(val,key){try{return this.setdata(JSON.stringify(val),key)}catch{return false}}; getScript(url){return new Promise((resolve)=>{this.get({url},(err,resp,body)=>resolve(body))})};runScript(script,runOpts){return new Promise((resolve)=>{let httpapi=this.getdata('@chavy_boxjs_userCfgs.httpapi');httpapi=httpapi?httpapi.replace(/\n/g,'').trim():httpapi;let httpapi_timeout=this.getdata('@chavy_boxjs_userCfgs.httpapi_timeout');httpapi_timeout=httpapi_timeout?httpapi_timeout*1:20;httpapi_timeout=runOpts&&runOpts.timeout?runOpts.timeout:httpapi_timeout;const[key,addr]=httpapi.split('@');const opts={url:`http://${addr}/v1/scripting/evaluate`,body:{script_text:script,mock_type:'cron',timeout:httpapi_timeout},headers:{'X-Key':key,'Accept':'*/*'}};this.post(opts,(err,resp,body)=>resolve(body))}).catch((e)=>this.logErr(e))};loaddata(){if(this.isNode()){this.fs=this.fs?this.fs:require('fs');this.path=this.path?this.path:require('path');const curDirDataFilePath=this.path.resolve(this.dataFile);const rootDirDataFilePath=this.path.resolve(process.cwd(),this.dataFile);const isCurDirDataFile=this.fs.existsSync(curDirDataFilePath);const isRootDirDataFile=!isCurDirDataFile&&this.fs.existsSync(rootDirDataFilePath);if(isCurDirDataFile||isRootDirDataFile){const datPath=isCurDirDataFile?curDirDataFilePath:rootDirDataFilePath;try{return JSON.parse(this.fs.readFileSync(datPath))}catch(e){return{}}}else return{}}else return{}};writedata(){if(this.isNode()){this.fs=this.fs?this.fs:require('fs');this.path=this.path?this.path:require('path');const curDirDataFilePath=this.path.resolve(this.dataFile);const rootDirDataFilePath=this.path.resolve(process.cwd(),this.dataFile);const isCurDirDataFile=this.fs.existsSync(curDirDataFilePath);const isRootDirDataFile=!isCurDirDataFile&&this.fs.existsSync(rootDirDataFilePath);const jsondata=JSON.stringify(this.data);if(isCurDirDataFile){this.fs.writeFileSync(curDirDataFilePath,jsondata)}else if(isRootDirDataFile){this.fs.writeFileSync(rootDirDataFilePath,jsondata)}else{this.fs.writeFileSync(curDirDataFilePath,jsondata)}}};lodash_get(source,path,defaultValue=undefined){const paths=path.replace(/\[(\d+)\]/g,'.$1').split('.');let result=source;for(const p of paths){result=Object(result)[p];if(result===undefined){return defaultValue}};return result};lodash_set(obj,path,value){if(Object(obj)!==obj)return obj;if(!Array.isArray(path))path=path.toString().match(/[^.[\]]+/g)||[];path.slice(0,-1).reduce((a,c,i)=>(Object(a[c])===a[c]?a[c]:(a[c]=Math.abs(path[i+1])>>0===+path[i+1]?[]:{})),obj)[path[path.length-1]]=value;return obj};getdata(key){let val=this.getval(key);if(/^@/.test(key)){const[,objkey,paths]=/^@(.*?)\.(.*?)$/.exec(key);const objval=objkey?this.getval(objkey):'';if(objval){try{const objedval=JSON.parse(objval);val=objedval?this.lodash_get(objedval,paths,''):val}catch(e){val=''}}};return val};setdata(val,key){let issuc=false;if(/^@/.test(key)){const[,objkey,paths]=/^@(.*?)\.(.*?)$/.exec(key);const objdat=this.getval(objkey);const objval=objkey?(objdat==='null'?null:objdat||'{}'):'{}';try{const objedval=JSON.parse(objval);this.lodash_set(objedval,paths,val);issuc=this.setval(JSON.stringify(objedval),objkey)}catch(e){const objedval={};this.lodash_set(objedval,paths,val);issuc=this.setval(JSON.stringify(objedval),objkey)}}else{issuc=this.setval(val,key)};return issuc};getval(key){if(this.isSurge()||this.isLoon()){return $persistentStore.read(key)}else if(this.isQuanX()){return $prefs.valueForKey(key)}else if(this.isNode()){this.data=this.loaddata();return this.data[key]}else{return(this.data&&this.data[key])||null}};setval(val,key){if(this.isSurge()||this.isLoon()){return $persistentStore.write(val,key)}else if(this.isQuanX()){return $prefs.setValueForKey(val,key)}else if(this.isNode()){this.data=this.loaddata(),this.data[key]=val,this.writedata();return true}else{return(this.data&&this.data[key])||null}};initGotEnv(opts){this.got=this.got?this.got:require('got');this.cktough=this.cktough?this.cktough:require('tough-cookie');this.ckjar=this.ckjar?this.ckjar:new this.cktough.CookieJar();if(opts){opts.headers=opts.headers?opts.headers:{};if(undefined===opts.headers.Cookie&&undefined===opts.cookieJar){opts.cookieJar=this.ckjar}}}; get(opts,callback=()=>{}){if(opts.headers){delete opts.headers['Content-Type'];delete opts.headers['Content-Length']};if(this.isSurge()||this.isLoon()){if(this.isSurge()&&this.isNeedRewrite){opts.headers=opts.headers||{};Object.assign(opts.headers,{'X-Surge-Skip-Scripting':false})};$httpClient.get(opts,(err,resp,body)=>{if(!err&&resp){resp.body=body,resp.statusCode=resp.status};callback(err,resp,body)})}else if(this.isQuanX()){if(this.isNeedRewrite){opts.opts=opts.opts||{};Object.assign(opts.opts,{hints:false})};$task.fetch(opts).then((resp)=>{const{statusCode:status,statusCode,headers,body}=resp;callback(null,{status,statusCode,headers,body},body)},(err)=>callback(err))}else if(this.isNode()){this.initGotEnv(opts);this.got(opts).on('redirect',(resp,nextOpts)=>{try{if(resp.headers['set-cookie']){const ck=resp.headers['set-cookie'].map(this.cktough.Cookie.parse).toString();if(ck){this.ckjar.setCookieSync(ck,null)};nextOpts.cookieJar=this.ckjar}}catch(e){this.logErr(e)}}).then((resp)=>{const{statusCode:status,statusCode,headers,body}=resp;callback(null,{status,statusCode,headers,body},body)},(err)=>{const{message:error,response:resp}=err;callback(error,resp,resp&&resp.body)})}};post(opts,callback=()=>{}){if(opts.body&&opts.headers&&!opts.headers['Content-Type']){opts.headers['Content-Type']='application/x-www-form-urlencoded'};if(opts.headers)delete opts.headers['Content-Length'];if(this.isSurge()||this.isLoon()){if(this.isSurge()&&this.isNeedRewrite){opts.headers=opts.headers||{};Object.assign(opts.headers,{'X-Surge-Skip-Scripting':false})};$httpClient.post(opts,(err,resp,body)=>{if(!err&&resp){resp.body=body,resp.statusCode=resp.status};callback(err,resp,body)})}else if(this.isQuanX()){opts.method='POST';if(this.isNeedRewrite){opts.opts=opts.opts||{};Object.assign(opts.opts,{hints:false})};$task.fetch(opts).then((resp)=>{const{statusCode:status,statusCode,headers,body}=resp;callback(null,{status,statusCode,headers,body},body)},(err)=>callback(err))}else if(this.isNode()){this.initGotEnv(opts);const{url,..._opts}=opts;this.got.post(url,_opts).then((resp)=>{const{statusCode:status,statusCode,headers,body}=resp;callback(null,{status,statusCode,headers,body},body)},(err)=>{const{message:error,response:resp}=err;callback(error,resp,resp&&resp.body)})}};time(fmt,ts=null){const date=ts?new Date(ts):new Date();var o={"M+":date.getMonth()+1,"d+":date.getDate(),"h":date.getHours()%12==0?12:date.getHours()/12<1?"上午"+date.getHours()%12:"下午"+date.getHours()%12,"H+":date.getHours(),"m+":date.getMinutes(),"s+":date.getSeconds(),"q+":Math.floor((date.getMonth()+3)/3),"S":date.getMilliseconds()};var week={"0":"\u65e5","1":"\u4e00","2":"\u4e8c","3":"\u4e09","4":"\u56db","5":"\u4e94","6":"\u516d"};if(/(y+)/.test(fmt)){fmt=fmt.replace(RegExp.$1,(date.getFullYear()+"").substr(4-RegExp.$1.length))};if(/(E+)/.test(fmt)){fmt=fmt.replace(RegExp.$1,((RegExp.$1.length>1)?(RegExp.$1.length>2?"\u661f\u671f":"\u5468"):"")+week[date.getDay()+""])};for(var k in o){if(new RegExp("("+k+")").test(fmt)){fmt=fmt.replace(RegExp.$1,(RegExp.$1.length==1)?(o[k]):(("00"+o[k]).substr((""+o[k]).length)))}};return fmt};msg(title=name,subt='',desc='',opts){const toEnvOpts=(rawopts)=>{if(!rawopts)return rawopts;if(typeof rawopts==='string'){if(this.isLoon())return rawopts;else if(this.isQuanX())return{'open-url':rawopts};else if(this.isSurge())return{url:rawopts};else return undefined}else if(typeof rawopts==='object'){if(this.isLoon()){let openUrl=rawopts.openUrl||rawopts.url||rawopts['open-url'];let mediaUrl=rawopts.mediaUrl||rawopts['media-url'];return{openUrl,mediaUrl}}else if(this.isQuanX()){let openUrl=rawopts['open-url']||rawopts.url||rawopts.openUrl;let mediaUrl=rawopts['media-url']||rawopts.mediaUrl;return{'open-url':openUrl,'media-url':mediaUrl}}else if(this.isSurge()){let openUrl=rawopts.url||rawopts.openUrl||rawopts['open-url'];return{url:openUrl}}}else{return undefined}};if(!this.isMute){if(this.isSurge()||this.isLoon()){$notification.post(title,subt,desc,toEnvOpts(opts))}else if(this.isQuanX()){$notify(title,subt,desc,toEnvOpts(opts))}};if(!this.isMuteLog){let logs=['','==============📣系统通知📣=============='];logs.push(title);subt?logs.push(subt):'';desc?logs.push(desc):'';console.log(logs.join('\n'));this.logs=this.logs.concat(logs)}};log(...logs){if(logs.length>0){this.logs=[...this.logs,...logs]};console.log(logs.join(this.logSeparator))};logErr(err,msg){const isPrintSack=!this.isSurge()&&!this.isQuanX()&&!this.isLoon();if(!isPrintSack){this.log('',`❗️${this.name}, 错误!`,err)}else{this.log('',`❗️${this.name}, 错误!`,err.stack)}};wait(time){return new Promise((resolve)=>setTimeout(resolve,time))};done(val={}){const endTime=new Date().getTime();const costTime=(endTime-this.startTime)/1000;this.log('',`🔔${this.name}, 结束! 🕛 ${costTime} 秒`);this.log();if(this.isSurge()||this.isQuanX()||this.isLoon()){$done(val)}}})(name,opts)} \ No newline at end of file diff --git a/Task/GithubActions.md b/Task/GithubActions.md index 81c2521d84..3596f7a82a 100644 --- a/Task/GithubActions.md +++ b/Task/GithubActions.md @@ -1,43 +1,55 @@ -# 关于本仓库 ***Actions Secrets*** 配置说明 :
- -

+

Actions Secrets 环境变量配置说明 :

- | Name | 脚本/相关YML | Value分割符 | 必须/可选 | 注意事项及样式 (其中"xxx"代表任意字符) | -| :---: | :---: | :--------------: | :---: | - | YOUTH_HEADER | **中青看点** youth.yml| # | 必须 | 请求地址: "https://kd.youth.cn/TaskCenter/getSign",
中青签到请求头: { xxx } | - | YOUTH_ARTBODY | 同上 | & | 必须 | 请求地址: "https://ios.baertt.com/v5/article/complete",
阅读请求体: p=xxx | - | YOUTH_REDBODY | 同上 | & | 必须 | 请求地址: "https://ios.baertt.com/v5/article/red_packet",
惊喜红包请求体: p=xxx | - | YOUTH_TIME | 同上 | & | 必须 | 请求地址: "https://ios.baertt.com/v5/user/app_stay.json",
阅读时长请求体: p=xxx | - | YOUTH_NOTIFY_CONTROL | 同上 | true/false | 可选 | 中青通知开关
默认当转盘次数为50或者100并且余额大于10元时推送通知 | - | | | | - | | - | YOUTH_READ | **中青阅读** youth_read.yml| &或者换行 | 必须 | 请求地址: "https://ios.baertt.com/v5/article/complete",
阅读请求体: p=xxx | - | | | | - | | - | TXNEWS_COOKIE | **腾讯新闻** txnews.yml| & | 必须 | 请求地址: "https://api.inews.qq.com/event/v1/user/event/report?",
腾讯新闻 Cookie: openxx=xxx | - | TXNEWS_SIGN | 同上 | # | 必须 | 请求地址同上, 阅读请求地址链接 | - | TXNEWS_VIDEO | 同上 | # | 必须 | 请求地址同上, 视频请求地址链接 | - | TXNEWS_NOTIFY_CONTROL | 同上 | true/false | 可选 | 腾讯新闻通知开关
默认当余额大于2元且通知间隔为50时推送通知 | - | | | | - | | - | DSJ_HEADERS | **电视家** dianshijia.yml | #或换行 | 必须 | 请求地址: "http://api.gaoqingdianshi.com/api/v2/sign/signin",
签到请求头: { xxx } | - | DSJ_DRAWAL | 同上 | #或换行 | 必须 | 请求地址: "http://api.gaoqingdianshi.com/api/v2/cash/withdrawal",
即提现请求地址 | - | DSJ_NOTIFY_CONTROL | 同上 | true/false | 可选 | 电视家通知开关
默认不推送 | - | | | | - | | - | WB_TOKEN | **新浪微博** weibo.yml | #或换行 | 必须 | 请求地址: "https://api.weibo.cn/xxx?gsid=",
签到token: gsid=xxx | - | WB_PAY | 同上 | #或换行 | 必须 | 请求地址: "https://pay.sc.weibo.com/aj/mobile/home/welfare/signin/do",
提现请求头 | - | | | | - | | - | JD_COOKIE | **京喜**
jingxi.yml | &或换行| 必须 | 京东cookie,多个账号的cookie使用`&`隔开或者换行。具体获取参考[浏览器获取京东cookie教程](https://github.com/lxk0301/scripts/blob/master/backUp/GetJdCookie.md) 或者 [插件获取京东cookie教程](https://github.com/lxk0301/scripts/blob/master/backUp/GetJdCookie2.md) | - | | | | - | | - | PUSH_KEY | 微信推送 | - | 可选 | cookie失效推送[server酱的微信通知](http://sc.ftqq.com/3.version) | - | BARK_PUSH | BARK推送 | - | 可选 | cookie失效推送BARK这个APP,填写内容是app提供的`设备码`,例如:https://api.day.app/123 ,那么此处的设备码就是`123`,再不懂看 [这个图](icon/bark.jpg) | - | BARK_SOUND | BARK推送 | - | 可选 | bark推送声音设置,例如`choo`,具体值请在`bark`-`推送铃声`-`查看所有铃声` | - | TG_BOT_TOKEN | telegram推送 | - | 可选 | tg推送,填写自己申请[@BotFather](https://t.me/BotFather)的Token,如`10xxx4:AAFcqxxxxgER5uw` , [具体教程](https://github.com/lxk0301/scripts/pull/37#issuecomment-692415594) | - | TG_USER_ID | telegram推送 | - | 可选 | tg推送,填写[@getuseridbot](https://t.me/getuseridbot)中获取到的纯数字ID, [具体教程](https://github.com/lxk0301/scripts/pull/37#issuecomment-692415594) | - | DD_BOT_TOKEN | 钉钉推送 | - | 可选 | 钉钉推送[官方文档](https://ding-doc.dingtalk.com/doc#/serverapi2/qf2nxq) ,只需`https://oapi.dingtalk.com/robot/send?access_token=XXX` 等于符号后面的XXX, 注:如果钉钉推送只填写`DD_BOT_TOKEN`,那么安全设置需勾选`自定义关键词`,内容输入输入`账号`即可,其他安全设置不要勾选 | - | DD_BOT_SECRET | 钉钉推送 | - | 可选 | 密钥,机器人安全设置页面,加签一栏下面显示的SEC开头的字符串 , 注:填写了`DD_BOT_TOKEN`和`DD_BOT_SECRET`,钉钉机器人安全设置只需勾选`加签`即可,其他选项不要勾选,再不懂看 [这个图](icon/DD_bot.png) | - - # 以上为配置方法详见[@lxk0301](https://raw.githubusercontent.com/lxk0301/scripts/master/githubAction.md) +| Name | 脚本相关YML | Value分割符 | 必须 / 可选 | 注意事项及样式(其中"xxx"代表任意字符) | +| :-------: | :------: | :-------: | ------ | ------- | +| YOUTH_HEADER | 中青看点 youth.yml | # | 必须 | 请求地址: "https://kd.youth.cn/WebApi/NewTaskIos/getTaskList",
中青签到请求头引用: uid=xxx&cookie_id=xxx&cookie=xxx| +| YOUTH_ARTBODY | 同上 | & | 必须 | 请求地址: "https://ios.baertt.com/v5/article/complete",
阅读请求体: p=xxx | +| YOUTH_REDBODY | 同上 | & | 必须 | 请求地址: "https://ios.baertt.com/v5/article/red_packet",
惊喜红包请求体: p=xxx | +| YOUTH_TIME | 同上 | & | 必须 | 请求地址: "https://ios.baertt.com/v5/user/app_stay.json",
阅读时长请求体: p=xxx | +| YOUTH_NOTIFY_CONTROL | 同上 | true/false | 可选 | 中青通知开关
默认当转盘次数为50或者100并且余额大于10元时推送通知 | +| | | | - | | +| YOUTH_READ | 中青阅读 youth_read.yml | &或者换行 | 必须 | 请求地址: "https://ios.baertt.com/v5/article/complete",
阅读请求体: p=xxx | +| YOUTH_START | 中青浏览赚 youth_gain.yml | & | 必须 | 请求地址: "https://ios.baertt.com/v5/task/browse_start.json",
阅读请求体: p=xxx | +| YOUTH_END | 同上 | & | 必须 | 请求地址: "https://ios.baertt.com/v5/task/browse_end.json",
阅读请求体: p=xxx | +| | | - | | | +| TXNEWS_COOKIE | 腾讯新闻 txnews.yml | & | 必须 | 请求地址: "https://api.inews.qq.com/event/v1/user/event/report?",
腾讯新闻 Cookie: openxx=xxx | +| TXNEWS_SIGN | 同上 | # | 必须 | 请求地址同上, 阅读请求地址链接 | +| TXNEWS_VIDEO | 同上 | # | 必须 | 请求地址同上, 视频请求地址链接 | +| TXNEWS_NOTIFY_CONTROL | 同上 | true/false | 可选 | 腾讯新闻通知开关
默认当余额大于2元且通知间隔为50时推送通知 | +| | | | - | | +| DSJ_HEADERS | 电视家dianshijia.yml | #或换行 | 必须 | 请求地址: "http://api.gaoqingdianshi.com/api/v2/sign/signin",
签到请求头: { xxx } | +| DSJ_DRAWAL | 同上 | #或换行 | 必须 | 请求地址: "http://api.gaoqingdianshi.com/api/v2/cash/withdrawal",
即提现请求地址 | +| DSJ_NOTIFY_CONTROL | 同上 | true/false | 可选 | 电视家通知开关
默认不推送 | +| | | | - | | +| WB_TOKEN | 微博 | #或换行 | 必须 | 请求地址: "https://api.weibo.cn/xxx?gsid=",
签到token: uid=xxx&gsid=xxx&s=xxx | +| | | | - | | + +
+ +
+ + + 相关通知推送 + + + +| Name | 脚本相关YML | Value分割符 | 必须 / 可选 | 注意事项及样式(其中"xxx"代表任意字符) | +| :-------: | :------: | ------- | ------ | ------- | +| PUSH_KEY | 微信推送 | - | 可选 | cookie失效推送[server酱的微信通知](http://sc.ftqq.com/3.version) | +| BARK_PUSH | BARK推送 | - | 可选 | cookie失效推送BARK这个APP,填写内容是app提供的`设备码`,例如:https://api.day.app/123 ,那么此处的设备码就是`123`,再不懂看 [这个图](icon/bark.jpg) | +| BARK_SOUND | BARK推送 | - | 可选 | bark推送声音设置,例如`choo`,具体值请在`bark`-`推送铃声`-`查看所有铃声` | +| TG_BOT_TOKEN | telegram推送 | - | 可选 | tg推送,填写自己申请[@BotFather](https://t.me/BotFather)的Token,如`10xxx4:AAFcqxxxxgER5uw` , [具体教程](https://github.com/lxk0301/scripts/pull/37#issuecomment-692415594) | +| TG_USER_ID | telegram推送 | - | 可选 | tg推送,填写[@getuseridbot](https://t.me/getuseridbot)中获取到的纯数字ID, [具体教程](https://github.com/lxk0301/scripts/pull/37#issuecomment-692415594) | +| DD_BOT_TOKEN | 钉钉推送 | - | 可选 | 钉钉推送[官方文档](https://ding-doc.dingtalk.com/doc#/serverapi2/qf2nxq) ,只需`https://oapi.dingtalk.com/robot/send?access_token=XXX` 等于符号后面的XXX, 注:如果钉钉推送只填写`DD_BOT_TOKEN`,那么安全设置需勾选`自定义关键词`,内容输入输入`账号`即可,其他安全设置不要勾选 | +| DD_BOT_SECRET | 钉钉推送 | - | 可选 | 密钥,机器人安全设置页面,加签一栏下面显示的SEC开头的字符串 , 注:填写了`DD_BOT_TOKEN`和`DD_BOT_SECRET`,钉钉机器人安全设置只需勾选`加签`即可,其他选项不要勾选,再不懂看 [这个图](icon/DD_bot.png) | + +
+ + ## 以上为配置方法详见[@lxk0301](https://raw.githubusercontent.com/lxk0301/jd_scripts/master/githubAction.md) +*** ## ***感谢*** - * [@lxk0301](https://t.me/lxk0301) - * [@chavy](https://t.me/chavyleung) + * [@lxk0301](https://t.me/lxk0301) + * [@chavy](https://t.me/chavyleung) \ No newline at end of file diff --git a/Task/README.md b/Task/README.md index d6aee70625..105a37bf35 100644 --- a/Task/README.md +++ b/Task/README.md @@ -21,7 +21,7 @@ ***您使用或者复制了本仓库且本人制作的任何脚本,则视为`已接受`此免责声明,请仔细阅读*** ####开发者不易,请赏杯茶水费 -
+
### 特别感谢: diff --git a/Task/Sunert_Task.json b/Task/Sunert_Task.json new file mode 100644 index 0000000000..3f8fae0e1c --- /dev/null +++ b/Task/Sunert_Task.json @@ -0,0 +1,76 @@ +{ + "name": "Sunert Task gallery", + "description": "https://github.com/Sunert/Scripts", + "task": [ + { + "config": "0 8 * * * https://raw.githubusercontent.com/Sunert/Scripts/master/Task/moji.js, tag=墨迹天气, img-url=https://raw.githubusercontent.com/Orz-3/mini/master/Color/moji.png, enabled=true" + }, + { + "config": "0 0 8 * * * https://raw.githubusercontent.com/Sunert/Scripts/master/Task/tvpreview.js, tag=节目预告, img-url=https://raw.githubusercontent.com/Sunert/Profiles/master/QuantumultX/Rules/Images/icon/tvpreview.png, enabled=true" + }, + { + "config": "0 0 8 * * * https://raw.githubusercontent.com/Sunert/Scripts/master/Task/trainquery.js, tag=12306火车时刻, img-url=https://raw.githubusercontent.com/Orz-3/mini/master/Color/12306.png, enabled=false" + }, + { + "config": "4 0 * * * https://raw.githubusercontent.com/Sunert/Scripts/master/Task/exchangeRate.js, tag=实时货币换算, img-url=https://raw.githubusercontent.com/Orz-3/mini/master/Color/exchangerate.png, enabled=false" + }, + { + "config": "7 10 * * * https://raw.githubusercontent.com/Sunert/Scripts/master/Task/translate.js, tag=谷歌中英互译, img-url=https://raw.githubusercontent.com/Orz-3/mini/master/Color/translate.png, enabled=false" + }, + { + "config": "0 0 8 * * * https://raw.githubusercontent.com/Sunert/Scripts/master/Task/telecomInfinity.js, tag=中国电信套餐, img-url=https://raw.githubusercontent.com/Orz-3/mini/master/Color/telecominfinty.png, enabled=true", + "addons": "https://raw.githubusercontent.com/Sunert/Scripts/master/TaskConf/dianxin/qx_rewite.txt, tag=dianxin_rewite, update-interval=-1, opt-parser=false, enabled=true" + }, + { + "config": "30 9 8 * * * https://raw.githubusercontent.com/Sunert/Scripts/master/Task/txnews.js, tag=腾讯新闻, img-url= https://raw.githubusercontent.com/Orz-3/mini/master/Color/txnews.png, enabled=true", + "addons": "https://raw.githubusercontent.com/Sunert/Scripts/master/TaskConf/txnews/qx_rewite.txt, tag=txnews_rewite, update-interval=-1, opt-parser=false, enabled=true" + }, + { + "config": "30 10 8 * * * https://raw.githubusercontent.com/Sunert/Scripts/master/Task/jddj.js, tag=京东到家, img-url=https://raw.githubusercontent.com/Orz-3/mini/master/Color/jddj.png, enabled=true", + "addons": "https://raw.githubusercontent.com/Sunert/Scripts/master/TaskConf/jd/qx_rewite.txt, tag=jd_rewite, update-interval=-1, opt-parser=false, enabled=true" + }, + { + "config": "40 10 8 * * * https://raw.githubusercontent.com/Sunert/Scripts/master/Task/lkyl.js, tag=来客有礼, img-url=https://raw.githubusercontent.com/Orz-3/mini/master/Color/lkyl.png, enabled=true", + "addons": "https://raw.githubusercontent.com/Sunert/Scripts/master/TaskConf/jd/qx_rewite.txt, tag=jd_rewite, update-interval=-1, opt-parser=false, enabled=true" + }, + { + "config": "0 0 7,22 * * * https://raw.githubusercontent.com/Sunert/Scripts/master/Task/dianshijia.js, tag=电视家, img-url=https://raw.githubusercontent.com/Orz-3/mini/master/Color/dianshijia.png, enabled=true", + "addons": "https://raw.githubusercontent.com/Sunert/Scripts/master/TaskConf/dianshijia/qx_rewite.txt, tag=dianshijia_rewite, update-interval=-1, opt-parser=false, enabled=true" + }, + { + "config": "0 11 8 * * * https://raw.githubusercontent.com/Sunert/Scripts/master/Task/kuaishou.js, tag=快手, img-url=https://raw.githubusercontent.com/Orz-3/mini/master/Color/kuaishou.png, enabled=true", + "addons": "https://raw.githubusercontent.com/Sunert/Scripts/master/TaskConf/kuaishou/qx_rewite.txt, tag=kuaishou_rewite, update-interval=-1, opt-parser=false, enabled=true" + }, + { + "config": "0 11 8 * * * https://raw.githubusercontent.com/Sunert/Scripts/master/Task/weibo.js, tag=微博&钱包, img-url=https://raw.githubusercontent.com/Orz-3/mini/master/Color/weibo.png, enabled=true", + "addons": "https://raw.githubusercontent.com/Sunert/Scripts/master/TaskConf/sina/qx_rewite.txt, tag=sina_rewite, update-interval=-1, opt-parser=false, enabled=true" + }, + { + "config": "10 11 8 * * * https://raw.githubusercontent.com/Sunert/Scripts/master/Task/sinanews.js, tag=新浪新闻, img-url=https://raw.githubusercontent.com/Orz-3/mini/master/Color/sinanews.png, enabled=true", + "addons": "https://raw.githubusercontent.com/Sunert/Scripts/master/TaskConf/sina/qx_rewite.txt, tag=sina_rewite, update-interval=-1, opt-parser=false, enabled=true" + }, + { + "config": "20 11 8 * * * https://raw.githubusercontent.com/Sunert/Scripts/master/Task/youth.js, tag=中青看点极速版, img-url=https://raw.githubusercontent.com/Orz-3/mini/master/Color/youth.png, enabled=true", + "addons": "https://raw.githubusercontent.com/Sunert/Scripts/master/TaskConf/youth/qx_rewite.txt, tag=youth_rewite, update-interval=-1, opt-parser=false, enabled=true" + }, + { + "config": "20 15 */2 * * * https://raw.githubusercontent.com/Sunert/Scripts/master/Task/Youth_Read.js, tag=中青自动阅读, img-url=https://raw.githubusercontent.com/Orz-3/mini/master/Color/youth.png, enabled=true", + "addons": "https://raw.githubusercontent.com/Sunert/Scripts/master/TaskConf/youth/qx_youthread.txt, tag=youth_auto, update-interval=-1, opt-parser=false, enabled=true" + }, + { + "config": "20 5 10 * * * https://raw.githubusercontent.com/Sunert/Scripts/master/Task/youth_gain.js, tag=中青浏览赚, img-url=https://raw.githubusercontent.com/Orz-3/mini/master/Color/youth.png, enabled=true", + "addons": "https://raw.githubusercontent.com/Sunert/Scripts/master/TaskConf/youth/qx_rewite.txt, tag=youth_rewite, update-interval=-1, opt-parser=false, enabled=true" + }, + { + "config": "4 0 * * * https://raw.githubusercontent.com/Sunert/Scripts/master/Task/mydigit.js, tag=数码之家, img-url=https://raw.githubusercontent.com/Orz-3/mini/master/Color/mydigit.png, enabled=true", + "addons": "https://raw.githubusercontent.com/Sunert/Scripts/master/TaskConf/digit_home/qx_rewite.txt, tag=mydigit_rewite, update-interval=-1, opt-parser=false, enabled=true" + }, + { + "config": "*/10 */3 * * * https://raw.githubusercontent.com/Sunert/Scripts/master/Task/jukan.js, tag=聚看点, img-url=https://raw.githubusercontent.com/Sunert/Profiles/master/QuantumultX/Rules/Images/icon/jukan.png, enabled=true", + "addons": "https://raw.githubusercontent.com/Sunert/Scripts/master/TaskConf/jukan/qx_rewite.txt, tag=jkd_rewite, update-interval=-1, opt-parser=false, enabled=true" + }, + { + "config": "*/30 * * * * https://raw.githubusercontent.com/Sunert/Scripts/master/Task/baidu_speed.js, tag=百度极速版, img-url=https://raw.githubusercontent.com/Sunert/Profiles/master/QuantumultX/Rules/Images/icon/baiduspeed.png, enabled=true" + } + ] +} diff --git a/Task/Youth_Read.js b/Task/Youth_Read.js index 54157ef15b..2b5b023c04 100644 --- a/Task/Youth_Read.js +++ b/Task/Youth_Read.js @@ -1,5 +1,5 @@ /* -更新时间: 2020-09-26 8:46 +更新时间: 2021-02-16 15:00 Github Actions使用方法见[@lxk0301](https://raw.githubusercontent.com/lxk0301/scripts/master/githubAction.md) 使用方法大同小异 请自行抓包,阅读文章和看视频,倒计时转一圈显示青豆到账即可,多看几篇文章和视频,获得更多包数据,抓包地址为"https://ios.baertt.com/v5/article/complete.json",在Github Actions中的Secrets新建name为'YOUTH_READ'的一个值,拷贝抓包的请求体到下面Value的文本框中,添加的请求体越多,获得青豆次数越多,本脚本不包含任何推送通知 @@ -8,77 +8,170 @@ Github Actions使用方法见[@lxk0301](https://raw.githubusercontent.com/lxk030 */ -let s = 30000 //等待延迟30s -const $ = new Env("中青看点") +const $ = new Env("中青看点阅读") //const notify = $.isNode() ? require('./sendNotify') : ''; -let ReadArr = [], YouthBody = "",readscore = 0; - if (process.env.YOUTH_READ && process.env.YOUTH_READ.indexOf('&') > -1) { - YouthBody = process.env.YOUTH_READ.split('&'); - console.log(`您选择的是用"&"隔开\n`) - } - else if (process.env.YOUTH_READ && process.env.YOUTH_READ.indexOf('\n') > -1) { - YouthBody = process.env.YOUTH_READ.split('\n'); - console.log(`您选择的是用换行隔开\n`) - } else { - YouthBody = process.env.YOUTH_READ.split() - } - Object.keys(YouthBody).forEach((item) => { - if (YouthBody[item]) { - ReadArr.push(YouthBody[item]) - } - }) - console.log(`============ 脚本执行-国际标准时间(UTC):${new Date().toLocaleString()} =============\n`) - console.log(`============ 脚本执行-北京时间(UTC+8):${new Date(new Date().getTime() + 8 * 60 * 60 * 1000).toLocaleString()} =============\n`) +let ReadArr = [], timebodyVal =""; +let YouthBody = $.getdata('youth_autoread')||$.getdata("zqgetbody_body"); +let artsnum = 0, videosnum = 0; +let videoscore = 0,readscore = 0; +if (isGetbody = typeof $request !==`undefined`) { + Getbody(); + $done() +} +let lastIndex = $.getdata('zqbody_index') +if(!$.isNode()&&!YouthBody==true){ + $.log("您未获取阅读请求,请求阅读后获取") + $.msg($.name, "您未获取阅读请求,请求阅读后获取","",{'open-url':"https://kandian.youth.cn/u/8S9DO"}) + return + } else if (!$.isNode() && YouthBody.indexOf("&") == -1) { + ReadArr.push(YouthBody) + } else { + if ($.isNode()) { + if (process.env.YOUTH_READ && process.env.YOUTH_READ.indexOf('&') > -1) { + YouthBody = process.env.YOUTH_READ.split('&'); + console.log(`您选择的是用"&"隔开\n`) + } else if (process.env.YOUTH_READ && process.env.YOUTH_READ.indexOf('\n') > -1) { + YouthBody = process.env.YOUTH_READ.split('\n'); + console.log(`您选择的是用换行隔开\n`) + } else { + YouthBody = [process.env.YOUTH_READ] + } + } else if (!$.isNode() && YouthBody.indexOf("&") > -1) { + YouthBody = YouthBody.split("&") + }; + Object.keys(YouthBody).forEach((item) =>{ + if (YouthBody[item]) { + ReadArr.push(YouthBody[item]) + } + }) + timeZone = new Date().getTimezoneOffset() / 60; + timestamp = Date.now()+ (8+timeZone) * 60 * 60 * 1000; + bjTime = new Date(timestamp).toLocaleString('zh',{hour12:false,timeZoneName: 'long'}); + console.log(`\n === 脚本执行 ${bjTime} ===\n`); + $.log("\n 您共获取"+ReadArr.length+"次阅读请求,任务开始\n") +} + !(async () => { if (!ReadArr[0]) { console.log($.name, '【提示】请把抓包的请求体填入Github 的 Secrets 中,请以&隔开') return; } - for (let i = 0; i < ReadArr.length; i++) { + +let indexLast = $.getdata('zqbody_index'); + $.begin = indexLast ? parseInt(indexLast,10) : 1; + $.index = 0; + $.log( "上次运行到第"+$.begin+"次终止,本次从"+(parseInt($.begin)+1)+"次开始"); + for ( var i = indexLast ? indexLast:0; i < ReadArr.length; i++) { if (ReadArr[i]) { articlebody = ReadArr[i]; - $.index = i + 1; - console.log(`-------------------------\n\n开始中青看点第${$.index}次阅读`) - } - await AutoRead(); + $.index = $.index + 1; + $.log(`-------------------------\n\n开始中青看点第${$.index}次阅读`); + await $.wait(10000); + await AutoRead(); + }; } - console.log(`-------------------------\n\n中青看点共完成${$.index}次阅读,共计获得${readscore}个青豆,阅读请求全部结束`) + $.log("本次共阅读"+artsnum+"次资讯,共获得"+readscore+"青豆\n观看"+videosnum+"次视频,获得"+videoscore+"青豆(不含0青豆次数)\n") + console.log(`-------------------------\n\n中青看点共完成${$.index}次阅读,共计获得${readscore+videoscore}个青豆,阅读请求全部结束`); + $.msg($.name, `本次运行共完成${$.index}次阅读,共计获得${readscore+videoscore}个青豆`) })() .catch((e) => $.logErr(e)) .finally(() => $.done()) function AutoRead() { - return new Promise((resolve, reject) => { - setTimeout(()=> { - let url = { - url: `https://ios.baertt.com/v5/article/complete.json`, - headers: { - 'User-Agent': 'KDApp/1.7.8 (iPhone; iOS 14.0; Scale/3.00)' - }, - body: articlebody + return new Promise((resolve, reject) =>{ + $.post(batHost('article/complete.json', articlebody), async(error, response, data) =>{ + let readres = JSON.parse(data); + // $.log(JSON.stringify(readres,null,2)) + $.begin=$.begin+1; + let res=$.begin%ReadArr.length + $.setdata(res+"", 'zqbody_index'); + if (readres.error_code == '0' && data.indexOf("read_score") > -1 && readres.items.read_score > 0) { + console.log(`\n本次阅读获得${readres.items.read_score}个青豆,请等待30s后执行下一次阅读\n`); + if(data.indexOf("ctype")>-1){ + if(readres.items.ctype==0){ + artsnum += 1 + readscore += parseInt(readres.items.read_score); + } else if(readres.items.ctype==3){ + videosnum += 1 + videoscore += parseInt(readres.items.read_score); + } + } + if ($.index % 2 == 0) { + if ($.isNode() && process.env.YOUTH_ATIME) { + timebodyVal = process.env.YOUTH_ATIME; + } else { + timebodyVal = $.getdata('autotime_zq'); + } + await readTime() }; - $.post(url, (error, response, data) => { - let readres = JSON.parse(data); - console.log(data) - if (readres.error_code == '0' && typeof readres.items.read_score === 'number') { - console.log(`\n本次阅读获得${readres.items.read_score}个青豆,即将开始下次阅读\n`) - readscore += readres.items.read_score - } - else if (readres.error_code == '0' && typeof readres.items.score === 'number') { - console.log(`\n本次阅读获得${readres.items.score}个青豆,即将开始下次阅读\n`) - readscore += readres.items.score - } - else if (readres.success == false){ - console.log(`第${$.index}次阅读请求有误,请删除此请求`) - } - else if (readres.items.max_notice == '\u770b\u592a\u4e45\u4e86\uff0c\u63621\u7bc7\u8bd5\u8bd5') { - console.log(readres.items.max_notice) + if($.index==ReadArr.length){ + $.log($.index+"次任务已全部完成,即将结束") + } else { + await $.wait(20000); + } + } else if (readres.error_code == '0' && data.indexOf('"score":0') > -1 && readres.items.score == 0) { + console.log(`\n本次阅读获得0个青豆,等待10s即将开始下次阅读\n`); + } else if (readres.success == false) { + console.log(`第${$.index}次阅读请求有误,请删除此请求`) + } else if (readres.items.max_notice == '\u770b\u592a\u4e45\u4e86\uff0c\u63621\u7bc7\u8bd5\u8bd5') { + console.log(readres.items.max_notice) + } + resolve() + }) + }) +} + +function batHost(api, body) { + return { + url: 'https://ios.baertt.com/v5/'+api, + headers: { + 'User-Agent': 'KDApp/2.0.0 (iPhone; iOS 14.5; Scale/3.00)', + 'Host': 'ios.baertt.com', + 'Content-Type': 'application/x-www-form-urlencoded' + }, + body: body + } +} + +function readTime() { + return new Promise((resolve, reject) => { + $.post(batHost('user/stay.json',timebodyVal), (error, resp, data) => { + let timeres = JSON.parse(data) + if (timeres.error_code == 0) { + readtimes = timeres.time / 60 + $.log(`阅读时长共计` + Math.floor(readtimes) + `分钟`) } - resolve() + resolve() }) - },s) }) } -function Env(t,e){class s{constructor(t){this.env=t}send(t,e="GET"){t="string"==typeof t?{url:t}:t;let s=this.get;return"POST"===e&&(s=this.post),new Promise((e,i)=>{s.call(this,t,(t,s,r)=>{t?i(t):e(s)})})}get(t){return this.send.call(this.env,t)}post(t){return this.send.call(this.env,t,"POST")}}return new class{constructor(t,e){this.name=t,this.http=new s(this),this.data=null,this.dataFile="box.dat",this.logs=[],this.isMute=!1,this.isNeedRewrite=!1,this.logSeparator="\n",this.startTime=(new Date).getTime(),Object.assign(this,e),this.log("",`\ud83d\udd14${this.name}, \u5f00\u59cb!`)}isNode(){return"undefined"!=typeof module&&!!module.exports}isQuanX(){return"undefined"!=typeof $task}isSurge(){return"undefined"!=typeof $httpClient&&"undefined"==typeof $loon}isLoon(){return"undefined"!=typeof $loon}toObj(t,e=null){try{return JSON.parse(t)}catch{return e}}toStr(t,e=null){try{return JSON.stringify(t)}catch{return e}}getjson(t,e){let s=e;const i=this.getdata(t);if(i)try{s=JSON.parse(this.getdata(t))}catch{}return s}setjson(t,e){try{return this.setdata(JSON.stringify(t),e)}catch{return!1}}getScript(t){return new Promise(e=>{this.get({url:t},(t,s,i)=>e(i))})}runScript(t,e){return new Promise(s=>{let i=this.getdata("@chavy_boxjs_userCfgs.httpapi");i=i?i.replace(/\n/g,"").trim():i;let r=this.getdata("@chavy_boxjs_userCfgs.httpapi_timeout");r=r?1*r:20,r=e&&e.timeout?e.timeout:r;const[o,h]=i.split("@"),a={url:`http://${h}/v1/scripting/evaluate`,body:{script_text:t,mock_type:"cron",timeout:r},headers:{"X-Key":o,Accept:"*/*"}};this.post(a,(t,e,i)=>s(i))}).catch(t=>this.logErr(t))}loaddata(){if(!this.isNode())return{};{this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(this.dataFile),e=this.path.resolve(process.cwd(),this.dataFile),s=this.fs.existsSync(t),i=!s&&this.fs.existsSync(e);if(!s&&!i)return{};{const i=s?t:e;try{return JSON.parse(this.fs.readFileSync(i))}catch(t){return{}}}}}writedata(){if(this.isNode()){this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(this.dataFile),e=this.path.resolve(process.cwd(),this.dataFile),s=this.fs.existsSync(t),i=!s&&this.fs.existsSync(e),r=JSON.stringify(this.data);s?this.fs.writeFileSync(t,r):i?this.fs.writeFileSync(e,r):this.fs.writeFileSync(t,r)}}lodash_get(t,e,s){const i=e.replace(/\[(\d+)\]/g,".$1").split(".");let r=t;for(const t of i)if(r=Object(r)[t],void 0===r)return s;return r}lodash_set(t,e,s){return Object(t)!==t?t:(Array.isArray(e)||(e=e.toString().match(/[^.[\]]+/g)||[]),e.slice(0,-1).reduce((t,s,i)=>Object(t[s])===t[s]?t[s]:t[s]=Math.abs(e[i+1])>>0==+e[i+1]?[]:{},t)[e[e.length-1]]=s,t)}getdata(t){let e=this.getval(t);if(/^@/.test(t)){const[,s,i]=/^@(.*?)\.(.*?)$/.exec(t),r=s?this.getval(s):"";if(r)try{const t=JSON.parse(r);e=t?this.lodash_get(t,i,""):e}catch(t){e=""}}return e}setdata(t,e){let s=!1;if(/^@/.test(e)){const[,i,r]=/^@(.*?)\.(.*?)$/.exec(e),o=this.getval(i),h=i?"null"===o?null:o||"{}":"{}";try{const e=JSON.parse(h);this.lodash_set(e,r,t),s=this.setval(JSON.stringify(e),i)}catch(e){const o={};this.lodash_set(o,r,t),s=this.setval(JSON.stringify(o),i)}}else s=this.setval(t,e);return s}getval(t){return this.isSurge()||this.isLoon()?$persistentStore.read(t):this.isQuanX()?$prefs.valueForKey(t):this.isNode()?(this.data=this.loaddata(),this.data[t]):this.data&&this.data[t]||null}setval(t,e){return this.isSurge()||this.isLoon()?$persistentStore.write(t,e):this.isQuanX()?$prefs.setValueForKey(t,e):this.isNode()?(this.data=this.loaddata(),this.data[e]=t,this.writedata(),!0):this.data&&this.data[e]||null}initGotEnv(t){this.got=this.got?this.got:require("got"),this.cktough=this.cktough?this.cktough:require("tough-cookie"),this.ckjar=this.ckjar?this.ckjar:new this.cktough.CookieJar,t&&(t.headers=t.headers?t.headers:{},void 0===t.headers.Cookie&&void 0===t.cookieJar&&(t.cookieJar=this.ckjar))}get(t,e=(()=>{})){t.headers&&(delete t.headers["Content-Type"],delete t.headers["Content-Length"]),this.isSurge()||this.isLoon()?(this.isSurge()&&this.isNeedRewrite&&(t.headers=t.headers||{},Object.assign(t.headers,{"X-Surge-Skip-Scripting":!1})),$httpClient.get(t,(t,s,i)=>{!t&&s&&(s.body=i,s.statusCode=s.status),e(t,s,i)})):this.isQuanX()?(this.isNeedRewrite&&(t.opts=t.opts||{},Object.assign(t.opts,{hints:!1})),$task.fetch(t).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>e(t))):this.isNode()&&(this.initGotEnv(t),this.got(t).on("redirect",(t,e)=>{try{if(t.headers["set-cookie"]){const s=t.headers["set-cookie"].map(this.cktough.Cookie.parse).toString();this.ckjar.setCookieSync(s,null),e.cookieJar=this.ckjar}}catch(t){this.logErr(t)}}).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>{const{message:s,response:i}=t;e(s,i,i&&i.body)}))}post(t,e=(()=>{})){if(t.body&&t.headers&&!t.headers["Content-Type"]&&(t.headers["Content-Type"]="application/x-www-form-urlencoded"),t.headers&&delete t.headers["Content-Length"],this.isSurge()||this.isLoon())this.isSurge()&&this.isNeedRewrite&&(t.headers=t.headers||{},Object.assign(t.headers,{"X-Surge-Skip-Scripting":!1})),$httpClient.post(t,(t,s,i)=>{!t&&s&&(s.body=i,s.statusCode=s.status),e(t,s,i)});else if(this.isQuanX())t.method="POST",this.isNeedRewrite&&(t.opts=t.opts||{},Object.assign(t.opts,{hints:!1})),$task.fetch(t).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>e(t));else if(this.isNode()){this.initGotEnv(t);const{url:s,...i}=t;this.got.post(s,i).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>{const{message:s,response:i}=t;e(s,i,i&&i.body)})}}time(t){let e={"M+":(new Date).getMonth()+1,"d+":(new Date).getDate(),"H+":(new Date).getHours(),"m+":(new Date).getMinutes(),"s+":(new Date).getSeconds(),"q+":Math.floor(((new Date).getMonth()+3)/3),S:(new Date).getMilliseconds()};/(y+)/.test(t)&&(t=t.replace(RegExp.$1,((new Date).getFullYear()+"").substr(4-RegExp.$1.length)));for(let s in e)new RegExp("("+s+")").test(t)&&(t=t.replace(RegExp.$1,1==RegExp.$1.length?e[s]:("00"+e[s]).substr((""+e[s]).length)));return t}msg(e=t,s="",i="",r){const o=t=>{if(!t)return t;if("string"==typeof t)return this.isLoon()?t:this.isQuanX()?{"open-url":t}:this.isSurge()?{url:t}:void 0;if("object"==typeof t){if(this.isLoon()){let e=t.openUrl||t.url||t["open-url"],s=t.mediaUrl||t["media-url"];return{openUrl:e,mediaUrl:s}}if(this.isQuanX()){let e=t["open-url"]||t.url||t.openUrl,s=t["media-url"]||t.mediaUrl;return{"open-url":e,"media-url":s}}if(this.isSurge()){let e=t.url||t.openUrl||t["open-url"];return{url:e}}}};this.isMute||(this.isSurge()||this.isLoon()?$notification.post(e,s,i,o(r)):this.isQuanX()&&$notify(e,s,i,o(r)));let h=["","==============\ud83d\udce3\u7cfb\u7edf\u901a\u77e5\ud83d\udce3=============="];h.push(e),s&&h.push(s),i&&h.push(i),console.log(h.join("\n")),this.logs=this.logs.concat(h)}log(...t){t.length>0&&(this.logs=[...this.logs,...t]),console.log(t.join(this.logSeparator))}logErr(t,e){const s=!this.isSurge()&&!this.isQuanX()&&!this.isLoon();s?this.log("",`\u2757\ufe0f${this.name}, \u9519\u8bef!`,t.stack):this.log("",`\u2757\ufe0f${this.name}, \u9519\u8bef!`,t)}wait(t){return new Promise(e=>setTimeout(e,t))}done(t={}){const e=(new Date).getTime(),s=(e-this.startTime)/1e3;this.log("",`\ud83d\udd14${this.name}, \u7ed3\u675f! \ud83d\udd5b ${s} \u79d2`),this.log(),(this.isSurge()||this.isQuanX()||this.isLoon())&&$done(t)}}(t,e)} \ No newline at end of file +function Getbody() { + if ($request && $request.method != `OPTIONS` && $request.url.match(/\/article\/info\/get/)) { + bodyVal = $request.url.split("?")[1]; + if (YouthBody) { + if (YouthBody.indexOf(bodyVal) > -1) { + $.log("此阅读请求已存在,本次跳过") + } else if (YouthBody.indexOf(bodyVal) == -1) { + YouthBodys = YouthBody + "&" + bodyVal; + $.setdata(YouthBodys, 'youth_autoread'); + $.log(`${$.name}获取阅读: 成功, YouthBodys: ${bodyVal}`); + bodys = YouthBodys.split("&") + $.msg($.name, "获取第"+bodys.length+"个阅读请求: 成功🎉", ``) + } + } else { + $.setdata(bodyVal, 'youth_autoread'); + $.log(`${$.name}获取阅读: 成功, YouthBodys: ${bodyVal}`); + $.msg($.name, `获取第一个阅读请求: 成功🎉`, ``) + } + } else if($request&&$request.method!=`OPTIONS`&&$request.url.match(/\/v5\/user\/stay/)){ + const timebodyVal=$request.body; + if(timebodyVal) $.setdata(timebodyVal,'autotime_zq'); + $.log(`${$.name}获取阅读时长: 成功, timebodyVal: ${timebodyVal}`); + $.msg($.name,`获取阅读时长: 成功🎉`,``) + } +} + + +function Env(t,e){class s{constructor(t){this.env=t}send(t,e="GET"){t="string"==typeof t?{url:t}:t;let s=this.get;return"POST"===e&&(s=this.post),new Promise((e,i)=>{s.call(this,t,(t,s,r)=>{t?i(t):e(s)})})}get(t){return this.send.call(this.env,t)}post(t){return this.send.call(this.env,t,"POST")}}return new class{constructor(t,e){this.name=t,this.http=new s(this),this.data=null,this.dataFile="box.dat",this.logs=[],this.isMute=!1,this.isNeedRewrite=!1,this.logSeparator="\n",this.startTime=(new Date).getTime(),Object.assign(this,e),this.log("",`\ud83d\udd14${this.name}, \u5f00\u59cb!`)}isNode(){return"undefined"!=typeof module&&!!module.exports}isQuanX(){return"undefined"!=typeof $task}isSurge(){return"undefined"!=typeof $httpClient&&"undefined"==typeof $loon}isLoon(){return"undefined"!=typeof $loon}toObj(t,e=null){try{return JSON.parse(t)}catch{return e}}toStr(t,e=null){try{return JSON.stringify(t)}catch{return e}}getjson(t,e){let s=e;const i=this.getdata(t);if(i)try{s=JSON.parse(this.getdata(t))}catch{}return s}setjson(t,e){try{return this.setdata(JSON.stringify(t),e)}catch{return!1}}getScript(t){return new Promise(e=>{this.get({url:t},(t,s,i)=>e(i))})}runScript(t,e){return new Promise(s=>{let i=this.getdata("@chavy_boxjs_userCfgs.httpapi");i=i?i.replace(/\n/g,"").trim():i;let r=this.getdata("@chavy_boxjs_userCfgs.httpapi_timeout");r=r?1*r:20,r=e&&e.timeout?e.timeout:r;const[o,h]=i.split("@"),a={url:`http://${h}/v1/scripting/evaluate`,body:{script_text:t,mock_type:"cron",timeout:r},headers:{"X-Key":o,Accept:"*/*"}};this.post(a,(t,e,i)=>s(i))}).catch(t=>this.logErr(t))}loaddata(){if(!this.isNode())return{};{this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(this.dataFile),e=this.path.resolve(process.cwd(),this.dataFile),s=this.fs.existsSync(t),i=!s&&this.fs.existsSync(e);if(!s&&!i)return{};{const i=s?t:e;try{return JSON.parse(this.fs.readFileSync(i))}catch(t){return{}}}}}writedata(){if(this.isNode()){this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(this.dataFile),e=this.path.resolve(process.cwd(),this.dataFile),s=this.fs.existsSync(t),i=!s&&this.fs.existsSync(e),r=JSON.stringify(this.data);s?this.fs.writeFileSync(t,r):i?this.fs.writeFileSync(e,r):this.fs.writeFileSync(t,r)}}lodash_get(t,e,s){const i=e.replace(/\[(\d+)\]/g,".$1").split(".");let r=t;for(const t of i)if(r=Object(r)[t],void 0===r)return s;return r}lodash_set(t,e,s){return Object(t)!==t?t:(Array.isArray(e)||(e=e.toString().match(/[^.[\]]+/g)||[]),e.slice(0,-1).reduce((t,s,i)=>Object(t[s])===t[s]?t[s]:t[s]=Math.abs(e[i+1])>>0==+e[i+1]?[]:{},t)[e[e.length-1]]=s,t)}getdata(t){let e=this.getval(t);if(/^@/.test(t)){const[,s,i]=/^@(.*?)\.(.*?)$/.exec(t),r=s?this.getval(s):"";if(r)try{const t=JSON.parse(r);e=t?this.lodash_get(t,i,""):e}catch(t){e=""}}return e}setdata(t,e){let s=!1;if(/^@/.test(e)){const[,i,r]=/^@(.*?)\.(.*?)$/.exec(e),o=this.getval(i),h=i?"null"===o?null:o||"{}":"{}";try{const e=JSON.parse(h);this.lodash_set(e,r,t),s=this.setval(JSON.stringify(e),i)}catch(e){const o={};this.lodash_set(o,r,t),s=this.setval(JSON.stringify(o),i)}}else s=this.setval(t,e);return s}getval(t){return this.isSurge()||this.isLoon()?$persistentStore.read(t):this.isQuanX()?$prefs.valueForKey(t):this.isNode()?(this.data=this.loaddata(),this.data[t]):this.data&&this.data[t]||null}setval(t,e){return this.isSurge()||this.isLoon()?$persistentStore.write(t,e):this.isQuanX()?$prefs.setValueForKey(t,e):this.isNode()?(this.data=this.loaddata(),this.data[e]=t,this.writedata(),!0):this.data&&this.data[e]||null}initGotEnv(t){this.got=this.got?this.got:require("got"),this.cktough=this.cktough?this.cktough:require("tough-cookie"),this.ckjar=this.ckjar?this.ckjar:new this.cktough.CookieJar,t&&(t.headers=t.headers?t.headers:{},void 0===t.headers.Cookie&&void 0===t.cookieJar&&(t.cookieJar=this.ckjar))}get(t,e=(()=>{})){t.headers&&(delete t.headers["Content-Type"],delete t.headers["Content-Length"]),this.isSurge()||this.isLoon()?(this.isSurge()&&this.isNeedRewrite&&(t.headers=t.headers||{},Object.assign(t.headers,{"X-Surge-Skip-Scripting":!1})),$httpClient.get(t,(t,s,i)=>{!t&&s&&(s.body=i,s.statusCode=s.status),e(t,s,i)})):this.isQuanX()?(this.isNeedRewrite&&(t.opts=t.opts||{},Object.assign(t.opts,{hints:!1})),$task.fetch(t).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>e(t))):this.isNode()&&(this.initGotEnv(t),this.got(t).on("redirect",(t,e)=>{try{if(t.headers["set-cookie"]){const s=t.headers["set-cookie"].map(this.cktough.Cookie.parse).toString();this.ckjar.setCookieSync(s,null),e.cookieJar=this.ckjar}}catch(t){this.logErr(t)}}).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>{const{message:s,response:i}=t;e(s,i,i&&i.body)}))}post(t,e=(()=>{})){if(t.body&&t.headers&&!t.headers["Content-Type"]&&(t.headers["Content-Type"]="application/x-www-form-urlencoded"),t.headers&&delete t.headers["Content-Length"],this.isSurge()||this.isLoon())this.isSurge()&&this.isNeedRewrite&&(t.headers=t.headers||{},Object.assign(t.headers,{"X-Surge-Skip-Scripting":!1})),$httpClient.post(t,(t,s,i)=>{!t&&s&&(s.body=i,s.statusCode=s.status),e(t,s,i)});else if(this.isQuanX())t.method="POST",this.isNeedRewrite&&(t.opts=t.opts||{},Object.assign(t.opts,{hints:!1})),$task.fetch(t).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>e(t));else if(this.isNode()){this.initGotEnv(t);const{url:s,...i}=t;this.got.post(s,i).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>{const{message:s,response:i}=t;e(s,i,i&&i.body)})}}time(t){let e={"M+":(new Date).getMonth()+1,"d+":(new Date).getDate(),"H+":(new Date).getHours(),"m+":(new Date).getMinutes(),"s+":(new Date).getSeconds(),"q+":Math.floor(((new Date).getMonth()+3)/3),S:(new Date).getMilliseconds()};/(y+)/.test(t)&&(t=t.replace(RegExp.$1,((new Date).getFullYear()+"").substr(4-RegExp.$1.length)));for(let s in e)new RegExp("("+s+")").test(t)&&(t=t.replace(RegExp.$1,1==RegExp.$1.length?e[s]:("00"+e[s]).substr((""+e[s]).length)));return t}msg(e=t,s="",i="",r){const o=t=>{if(!t)return t;if("string"==typeof t)return this.isLoon()?t:this.isQuanX()?{"open-url":t}:this.isSurge()?{url:t}:void 0;if("object"==typeof t){if(this.isLoon()){let e=t.openUrl||t.url||t["open-url"],s=t.mediaUrl||t["media-url"];return{openUrl:e,mediaUrl:s}}if(this.isQuanX()){let e=t["open-url"]||t.url||t.openUrl,s=t["media-url"]||t.mediaUrl;return{"open-url":e,"media-url":s}}if(this.isSurge()){let e=t.url||t.openUrl||t["open-url"];return{url:e}}}};this.isMute||(this.isSurge()||this.isLoon()?$notification.post(e,s,i,o(r)):this.isQuanX()&&$notify(e,s,i,o(r)));let h=["","==============\ud83d\udce3\u7cfb\u7edf\u901a\u77e5\ud83d\udce3=============="];h.push(e),s&&h.push(s),i&&h.push(i),console.log(h.join("\n")),this.logs=this.logs.concat(h)}log(...t){t.length>0&&(this.logs=[...this.logs,...t]),console.log(t.join(this.logSeparator))}logErr(t,e){const s=!this.isSurge()&&!this.isQuanX()&&!this.isLoon();s?this.log("",`\u2757\ufe0f${this.name}, \u9519\u8bef!`,t.stack):this.log("",`\u2757\ufe0f${this.name}, \u9519\u8bef!`,t)}wait(t){return new Promise(e=>setTimeout(e,t))}done(t={}){const e=(new Date).getTime(),s=(e-this.startTime)/1e3;this.log("",`\ud83d\udd14${this.name}, \u7ed3\u675f! \ud83d\udd5b ${s} \u79d2`),this.log(),(this.isSurge()||this.isQuanX()||this.isLoon())&&$done(t)}}(t,e)} diff --git a/Task/backup/beatPay.js b/Task/backup/beatPay.js new file mode 100644 index 0000000000..c357f14be9 --- /dev/null +++ b/Task/backup/beatPay.js @@ -0,0 +1,175 @@ +/* +更新时间: 2021-02-20 20:50 +https:\/\/czapp\.bestpay\.com\.cn\/payassistant-client\?method=queryPhoneBalance url script-request-body bestPay.js +hostname = czapp.bestpay.com.cn +翼支付打开权益专区,点击套餐详情,重进翼支付App时需重新获取请求,即重写配置不必禁用 + +*/ +const $ = new Env('翼支付电信套餐'); +const bodyVal = $.getdata('bestpay_tele'); +const queryTime = $.getdata('bestpay_bill').replace("-","")||parseInt($.time("yyyyMM")-1); +const cash = $.getdata('tele_balance')||"10"; + +let isGetCookie = typeof $request !== 'undefined' +if (isGetCookie) { + GetCookie() +} else { +!(async () => { + await queryBalance(); + await queryResource(); + await queryBill(); + $.msg($.name,$.sub,$.desc) +})() + .catch((e) => $.logErr(e)) + .finally(() => $.done()) +} +function GetCookie() { + if ($request.body) { + var bodyValue = $request.body; + if ($.getdata('bestpay_tele') != (undefined || null)) { + if ($.getdata('bestpay_tele') != bodyValue) { + var bodys = $.setdata(bodyValue, 'bestpay_tele'); + if (!bodys) { + $.msg("更新" + $.name + "请求失败‼️", "", ""); + $.log(`获取请求体: 失败`); + } else { + $.msg("更新" + $.name + "请求成功 🎉", "", ""); + $.log($.name+`, 获取请求: 成功, body: ${bodyValue}`) + } + } + } else { + var bodys = $.setdata(bodyValue, 'bestpay_tele'); + if (!bodys) { + $.msg("首次写入" + $.name + "请求失败‼️", "", ""); + } else { + $.msg("首次写入" + $.name + "请求成功 🎉", "", ""); + } + } + } else { + $.msg("写入" + $.name + "请求失败‼️", "", "配置错误, 无法读取请求体, "); + } + $.done() +} + + +function config(api,queryApi) { + return { + url:'https://czapp.bestpay.com.cn/payassistant-client?method='+api, + headers:{ + Host: 'czapp.bestpay.com.cn', + Referer: 'https://h5.bestpay.com.cn/subapps/payassistant/payassistant-new/index.html?hybridVersion=3.0&channel=quanyi', + 'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 Bestpay/10.1.91 hybridVersion/3.0 /sa-sdk-ios', + 'Content-Type': 'application/x-www-form-urlencoded' + }, + body: bodyVal+"&"+queryApi + } +} + + +function queryResource() { + return new Promise((resolve) =>{ + $.post(config('queryUserResource', 'BILLCYCLE='+$.time("yyyyMM")), (error, resp, data) =>{ + let result = JSON.parse(data); + try { + if (result.RESPONSECODE == "000000") { + products = result.RESULTDATASET; + //$.log(JSON.stringify(products,null,2)); + $.desc = "使用详情:\n"; + $.log("已开套餐:") + for (x in products) { + productsname = products[x].PRODUCTOFFNAME, + offerType = products[x].OFFERTYPE, + ratableid = products[x].RATABLERESOURCEID; + $.log(" "+productsname+" 类型:"+offerType); + if (ratableid) { + unitType = products[x].UNITTYPEID, + ratableName = products[x].RATABLERESOURCENAME, + mainname = productsname, + ratableAmount = products[x].RATABLEAMOUNT, + balanceAmount = products[x].BALANCEAMOUNT, + usageAmount = products[x].USAGEAMOUNT; + if(unitType !== "KB") { + usageAmount += unitType, + ratableAmount += unitType , + balanceAmount += unitType + } else if (unitType == "KB") { + usageAmount = formatFlow(usageAmount), + ratableAmount = formatFlow(ratableAmount), + balanceAmount = formatFlow(balanceAmount); + ratableName = ratableName?ratableName:productsname; + } + $.desc += " "+ratableName +":"+(balanceAmount?"总计:"+ratableAmount+" 使用:"+usageAmount+" 剩余:"+balanceAmount+"\n":""); + } + } + $.log("\n"+$.desc) + } + } catch(e) { + $.log("查询套餐信息错误"+ $.log(JSON.stringify(result,null,2))) + } finally { + resolve() + } + }) + }) +} + +function queryBill() { + return new Promise((resolve) =>{ + $.post(config('detailBillQueryNew', 'BILLCYCLE=' + queryTime), (error, resp, data) =>{ + let result = JSON.parse(data); + $.log(queryTime+"期账单明细:") + $.desc += queryTime+"期账单明细:\n" + try { + billDate = result.BILLINGCYCLE, + userName = result.customerName, + cashTotal = result.TOTAL / 100, + discount = result.CHARGEFREEDISCOUNT / 100, + mustPay = result.CHARGECORPUSDISCOUNT / 100; + for (lists of result.RESULTDATASET) { + billName = lists.CHARGETYPENAME, + billCharge = lists.CHARGE / 100; + $.desc += " "+billName + " 费用 " + billCharge + "元\n" + $.log(" "+billName + " 费用 " + billCharge + "元") + } + } catch(e) { + $.log("获取账单明细失败" + $.log(JSON.stringify(result, null, 2))) + } finally { + resolve() + } + }) + }) +} + +function queryBalance() { + return new Promise((resolve) =>{ + $.post(config('queryPhoneBalance'), (error, resp, data) =>{ + let result = JSON.parse(data); + try { + addressCity = result.CITYNAME, + teleNO = result.PRODUCTNO, + teleNO = teleNO.substr(0,3)+"****"+teleNO.substr(7) + balance = result.TELEBALANCE / 100, + userBalance = result.USAGEAMOUNT, + payAmount = result.payAmount / 100, + comBalance = result.COMBALANCE / 100; + if (balance < cash) { + $.msg($.name, "您的号码: " + teleNO + " 余额为" + balance + "元", "余额小于" + cash + "元,请您及时充值") + } + $.sub = "归属地:"+addressCity+" 号码:"+teleNO+" 余额:"+balance+"元" + } catch(e) { + $.log("获取手机余额失败" + $.log(JSON.stringify(result, null, 2))) + } finally { + resolve() + } + }) + }) +} + +function formatFlow(number) { + if (number/1024 < 1024) { + return (number/1024).toFixed(2) + "MB" + } + return (number/1024/1024).toFixed(2) + "GB" +} + + +function Env(name,opts){class Http{constructor(env){this.env=env};send(opts,method='GET'){opts=typeof opts==='string'?{url:opts}:opts;let sender=this.get;if(method==='POST'){sender=this.post};return new Promise((resolve,reject)=>{sender.call(this,opts,(err,resp,body)=>{if(err)reject(err);else resolve(resp)})})};get(opts){return this.send.call(this.env,opts)};post(opts){return this.send.call(this.env,opts,'POST')}};return new(class{constructor(name,opts){this.name=name,this.http=new Http(this),this.data=null,this.dataFile='box.dat',this.logs=[],this.isMute=false,this.isNeedRewrite=false,this.logSeparator='\n';this.startTime=new Date().getTime();Object.assign(this,opts);this.log('',`🔔${this.name}, 开始!`)};isNode(){return'undefined'!==typeof module&&!!module.exports};isQuanX(){return'undefined'!==typeof $task};isSurge(){return'undefined'!==typeof $httpClient&&'undefined'===typeof $loon};isLoon(){return'undefined'!==typeof $loon};toObj(str,defaultValue=null){try{return JSON.parse(str)}catch{return defaultValue}};toStr(obj,defaultValue=null){try{return JSON.stringify(obj)}catch{return defaultValue}};getjson(key,defaultValue){let json=defaultValue;const val=this.getdata(key);if(val){try{json=JSON.parse(this.getdata(key))}catch{}};return json};setjson(val,key){try{return this.setdata(JSON.stringify(val),key)}catch{return false}}; getScript(url){return new Promise((resolve)=>{this.get({url},(err,resp,body)=>resolve(body))})};runScript(script,runOpts){return new Promise((resolve)=>{let httpapi=this.getdata('@chavy_boxjs_userCfgs.httpapi');httpapi=httpapi?httpapi.replace(/\n/g,'').trim():httpapi;let httpapi_timeout=this.getdata('@chavy_boxjs_userCfgs.httpapi_timeout');httpapi_timeout=httpapi_timeout?httpapi_timeout*1:20;httpapi_timeout=runOpts&&runOpts.timeout?runOpts.timeout:httpapi_timeout;const[key,addr]=httpapi.split('@');const opts={url:`http://${addr}/v1/scripting/evaluate`,body:{script_text:script,mock_type:'cron',timeout:httpapi_timeout},headers:{'X-Key':key,'Accept':'*/*'}};this.post(opts,(err,resp,body)=>resolve(body))}).catch((e)=>this.logErr(e))};loaddata(){if(this.isNode()){this.fs=this.fs?this.fs:require('fs');this.path=this.path?this.path:require('path');const curDirDataFilePath=this.path.resolve(this.dataFile);const rootDirDataFilePath=this.path.resolve(process.cwd(),this.dataFile);const isCurDirDataFile=this.fs.existsSync(curDirDataFilePath);const isRootDirDataFile=!isCurDirDataFile&&this.fs.existsSync(rootDirDataFilePath);if(isCurDirDataFile||isRootDirDataFile){const datPath=isCurDirDataFile?curDirDataFilePath:rootDirDataFilePath;try{return JSON.parse(this.fs.readFileSync(datPath))}catch(e){return{}}}else return{}}else return{}};writedata(){if(this.isNode()){this.fs=this.fs?this.fs:require('fs');this.path=this.path?this.path:require('path');const curDirDataFilePath=this.path.resolve(this.dataFile);const rootDirDataFilePath=this.path.resolve(process.cwd(),this.dataFile);const isCurDirDataFile=this.fs.existsSync(curDirDataFilePath);const isRootDirDataFile=!isCurDirDataFile&&this.fs.existsSync(rootDirDataFilePath);const jsondata=JSON.stringify(this.data);if(isCurDirDataFile){this.fs.writeFileSync(curDirDataFilePath,jsondata)}else if(isRootDirDataFile){this.fs.writeFileSync(rootDirDataFilePath,jsondata)}else{this.fs.writeFileSync(curDirDataFilePath,jsondata)}}};lodash_get(source,path,defaultValue=undefined){const paths=path.replace(/\[(\d+)\]/g,'.$1').split('.');let result=source;for(const p of paths){result=Object(result)[p];if(result===undefined){return defaultValue}};return result};lodash_set(obj,path,value){if(Object(obj)!==obj)return obj;if(!Array.isArray(path))path=path.toString().match(/[^.[\]]+/g)||[];path.slice(0,-1).reduce((a,c,i)=>(Object(a[c])===a[c]?a[c]:(a[c]=Math.abs(path[i+1])>>0===+path[i+1]?[]:{})),obj)[path[path.length-1]]=value;return obj};getdata(key){let val=this.getval(key);if(/^@/.test(key)){const[,objkey,paths]=/^@(.*?)\.(.*?)$/.exec(key);const objval=objkey?this.getval(objkey):'';if(objval){try{const objedval=JSON.parse(objval);val=objedval?this.lodash_get(objedval,paths,''):val}catch(e){val=''}}};return val};setdata(val,key){let issuc=false;if(/^@/.test(key)){const[,objkey,paths]=/^@(.*?)\.(.*?)$/.exec(key);const objdat=this.getval(objkey);const objval=objkey?(objdat==='null'?null:objdat||'{}'):'{}';try{const objedval=JSON.parse(objval);this.lodash_set(objedval,paths,val);issuc=this.setval(JSON.stringify(objedval),objkey)}catch(e){const objedval={};this.lodash_set(objedval,paths,val);issuc=this.setval(JSON.stringify(objedval),objkey)}}else{issuc=this.setval(val,key)};return issuc};getval(key){if(this.isSurge()||this.isLoon()){return $persistentStore.read(key)}else if(this.isQuanX()){return $prefs.valueForKey(key)}else if(this.isNode()){this.data=this.loaddata();return this.data[key]}else{return(this.data&&this.data[key])||null}};setval(val,key){if(this.isSurge()||this.isLoon()){return $persistentStore.write(val,key)}else if(this.isQuanX()){return $prefs.setValueForKey(val,key)}else if(this.isNode()){this.data=this.loaddata(),this.data[key]=val,this.writedata();return true}else{return(this.data&&this.data[key])||null}};initGotEnv(opts){this.got=this.got?this.got:require('got');this.cktough=this.cktough?this.cktough:require('tough-cookie');this.ckjar=this.ckjar?this.ckjar:new this.cktough.CookieJar();if(opts){opts.headers=opts.headers?opts.headers:{};if(undefined===opts.headers.Cookie&&undefined===opts.cookieJar){opts.cookieJar=this.ckjar}}}; get(opts,callback=()=>{}){if(opts.headers){delete opts.headers['Content-Type'];delete opts.headers['Content-Length']};if(this.isSurge()||this.isLoon()){if(this.isSurge()&&this.isNeedRewrite){opts.headers=opts.headers||{};Object.assign(opts.headers,{'X-Surge-Skip-Scripting':false})};$httpClient.get(opts,(err,resp,body)=>{if(!err&&resp){resp.body=body,resp.statusCode=resp.status};callback(err,resp,body)})}else if(this.isQuanX()){if(this.isNeedRewrite){opts.opts=opts.opts||{};Object.assign(opts.opts,{hints:false})};$task.fetch(opts).then((resp)=>{const{statusCode:status,statusCode,headers,body}=resp;callback(null,{status,statusCode,headers,body},body)},(err)=>callback(err))}else if(this.isNode()){this.initGotEnv(opts);this.got(opts).on('redirect',(resp,nextOpts)=>{try{if(resp.headers['set-cookie']){const ck=resp.headers['set-cookie'].map(this.cktough.Cookie.parse).toString();if(ck){this.ckjar.setCookieSync(ck,null)};nextOpts.cookieJar=this.ckjar}}catch(e){this.logErr(e)}}).then((resp)=>{const{statusCode:status,statusCode,headers,body}=resp;callback(null,{status,statusCode,headers,body},body)},(err)=>{const{message:error,response:resp}=err;callback(error,resp,resp&&resp.body)})}};post(opts,callback=()=>{}){if(opts.body&&opts.headers&&!opts.headers['Content-Type']){opts.headers['Content-Type']='application/x-www-form-urlencoded'};if(opts.headers)delete opts.headers['Content-Length'];if(this.isSurge()||this.isLoon()){if(this.isSurge()&&this.isNeedRewrite){opts.headers=opts.headers||{};Object.assign(opts.headers,{'X-Surge-Skip-Scripting':false})};$httpClient.post(opts,(err,resp,body)=>{if(!err&&resp){resp.body=body,resp.statusCode=resp.status};callback(err,resp,body)})}else if(this.isQuanX()){opts.method='POST';if(this.isNeedRewrite){opts.opts=opts.opts||{};Object.assign(opts.opts,{hints:false})};$task.fetch(opts).then((resp)=>{const{statusCode:status,statusCode,headers,body}=resp;callback(null,{status,statusCode,headers,body},body)},(err)=>callback(err))}else if(this.isNode()){this.initGotEnv(opts);const{url,..._opts}=opts;this.got.post(url,_opts).then((resp)=>{const{statusCode:status,statusCode,headers,body}=resp;callback(null,{status,statusCode,headers,body},body)},(err)=>{const{message:error,response:resp}=err;callback(error,resp,resp&&resp.body)})}};time(fmt,ts=null){const date=ts?new Date(ts):new Date();var o={"M+":date.getMonth()+1,"d+":date.getDate(),"h":date.getHours()%12==0?12:date.getHours()/12<1?"上午"+date.getHours()%12:"下午"+date.getHours()%12,"H+":date.getHours(),"m+":date.getMinutes(),"s+":date.getSeconds(),"q+":Math.floor((date.getMonth()+3)/3),"S":date.getMilliseconds()};var week={"0":"\u65e5","1":"\u4e00","2":"\u4e8c","3":"\u4e09","4":"\u56db","5":"\u4e94","6":"\u516d"};if(/(y+)/.test(fmt)){fmt=fmt.replace(RegExp.$1,(date.getFullYear()+"").substr(4-RegExp.$1.length))};if(/(E+)/.test(fmt)){fmt=fmt.replace(RegExp.$1,((RegExp.$1.length>1)?(RegExp.$1.length>2?"\u661f\u671f":"\u5468"):"")+week[date.getDay()+""])};for(var k in o){if(new RegExp("("+k+")").test(fmt)){fmt=fmt.replace(RegExp.$1,(RegExp.$1.length==1)?(o[k]):(("00"+o[k]).substr((""+o[k]).length)))}};return fmt};msg(title=name,subt='',desc='',opts){const toEnvOpts=(rawopts)=>{if(!rawopts)return rawopts;if(typeof rawopts==='string'){if(this.isLoon())return rawopts;else if(this.isQuanX())return{'open-url':rawopts};else if(this.isSurge())return{url:rawopts};else return undefined}else if(typeof rawopts==='object'){if(this.isLoon()){let openUrl=rawopts.openUrl||rawopts.url||rawopts['open-url'];let mediaUrl=rawopts.mediaUrl||rawopts['media-url'];return{openUrl,mediaUrl}}else if(this.isQuanX()){let openUrl=rawopts['open-url']||rawopts.url||rawopts.openUrl;let mediaUrl=rawopts['media-url']||rawopts.mediaUrl;return{'open-url':openUrl,'media-url':mediaUrl}}else if(this.isSurge()){let openUrl=rawopts.url||rawopts.openUrl||rawopts['open-url'];return{url:openUrl}}}else{return undefined}};if(!this.isMute){if(this.isSurge()||this.isLoon()){$notification.post(title,subt,desc,toEnvOpts(opts))}else if(this.isQuanX()){$notify(title,subt,desc,toEnvOpts(opts))}};if(!this.isMuteLog){let logs=['','==============📣\u7CFB\u7EDF\u901A\u77E5📣=============='];logs.push(title);subt?logs.push(subt):'';desc?logs.push(desc):'';console.log(logs.join('\n'));this.logs=this.logs.concat(logs)}};log(...logs){if(logs.length>0){this.logs=[...this.logs,...logs]};console.log(logs.join(this.logSeparator))};logErr(err,msg){const isPrintSack=!this.isSurge()&&!this.isQuanX()&&!this.isLoon();if(!isPrintSack){this.log('',`❗️${this.name}, \u9519\u8BEF!`,err)}else{this.log('',`❗️${this.name}, \u9519\u8BEF!`,err.stack)}};wait(time){return new Promise((resolve)=>setTimeout(resolve,time))};done(val={}){const endTime=new Date().getTime();const costTime=(endTime-this.startTime)/1000;this.log('',`🔔${this.name}, \u7ED3\u675F! 🕛 ${costTime} \u79D2`);this.log();if(this.isSurge()||this.isQuanX()||this.isLoon()){$done(val)}}})(name,opts)} diff --git a/Task/backup/tele_p5.js b/Task/backup/tele_p5.js new file mode 100644 index 0000000000..78a5680fc4 --- /dev/null +++ b/Task/backup/tele_p5.js @@ -0,0 +1,172 @@ +/* +更新时间: 2021-02-20 20:50 +https:\/\/czapp\.bestpay\.com\.cn\/payassistant-client\?method=queryPhoneBalance url script-request-body bestPay.js +hostname = czapp.bestpay.com.cn +翼支付打开权益专区,点击套餐详情,重进翼支付App时需重新获取请求,即重写配置不必禁用 + +*/ +const $ = new Env('电信套餐'); +const cookieVal = $.getdata('p5_tele'); +const queryTime = $.getdata('bestpay_bill').replace("-","")||parseInt($.time("yyyyMM")-1); +const cash = $.getdata('tele_balance')||"10"; + +let isGetCookie = typeof $request !== 'undefined' +if (isGetCookie) { + GetCookie() +} else { +!(async () => { + //await queryBalance(); + await queryResource(); + await queryBill(); + $.msg($.name,$.sub,$.desc) +})() + .catch((e) => $.logErr(e)) + .finally(() => $.done()) +} +function GetCookie() { + if ($request.headers) { + var bodyValue = $request.headers['Cookie']; + if ($.getdata('p5_tele') != (undefined || null)) { + if ($.getdata('p5_tele') != bodyValue) { + var bodys = $.setdata(bodyValue, 'p5_tele'); + if (!bodys) { + $.msg("更新" + $.name + "请求失败‼️", "", ""); + $.log(`获取请求体: 失败`); + } else { + $.msg("更新" + $.name + "请求成功 🎉", "", ""); + $.log($.name+`, 获取请求: 成功, body: ${bodyValue}`) + } + } + } else { + var bodys = $.setdata(bodyValue, 'p5_tele'); + if (!bodys) { + $.msg("首次写入" + $.name + "请求失败‼️", "", ""); + } else { + $.msg("首次写入" + $.name + "请求成功 🎉", "", ""); + } + } + } else { + $.msg("写入" + $.name + "请求失败‼️", "", "配置错误, 无法读取请求体, "); + } + $.done() +} + + +function config(api,body) { + return { + url:'http://zj.189.cn/zjpr/'+api, + headers:{ + Host: 'zj.189.cn', + Referer: 'http://zj.189.cn/zjpr/servicenew/tcAmount/tcAmount.html?menuFlag=1', + 'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; Win64, x64; Trident/7.0; rv:11.0) like Gecko', + 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', + 'Cookie': cookieVal + }, + body: body + } +} + + +function queryResource() { + return new Promise((resolve) =>{ + $.post(config('servicenew/tcAmount/queryTaoCan.html','queryDate=202102&type=2'), (error, resp, data) =>{ + let result = JSON.parse(data); +//$.log(JSON.stringify(result,null,2)); + try { + if (result.result){ + $.msg($.name,result.result,""); + return + } else { + //$.desc = '语音套餐\n' + for(yuyin of result.yuyinList){ + productName = yuyin.ProductName + ResName = yuyin.FreeResName + yuyinTotal = yuyin.FreeResLimit + yuyinBalance = yuyin.otherSurplusAmount; + yuyinUsed = yuyin.FreeResUsed + Unit = yuyin.ResUnit + $.desc += productName+':\n '+ResName+':总计'+yuyinTotal+Unit+' 已用'+yuyinUsed+Unit+' 剩余'+yuyinBalance+Unit+'\n' + + }; + //$.desc += '流量套餐\n'; + for(datas of result.ll_country_details){ + productName = datas.ProductName + ResName = datas.FreeResTypeName + dataTotal = datas.FreeResLimit + dataBalance = datas.promSurplusAmount; + dataUsed = datas.FreeResUsed + $.desc += productName+':\n '+ResName+':总计'+formatFlow(dataTotal)+' 已用'+formatFlow(dataUsed)+' 剩余'+formatFlow(dataBalance)+'\n' + } + } + } catch(e) { + $.log("查询套餐信息错误"+ $.log(JSON.stringify(result,null,2))) + } finally { + resolve() + } + }) + }) +} + +function queryBill() { + return new Promise((resolve) =>{ + $.post(config('bill/queryUopBillInfo.htm', 'billMonth=' + queryTime), (error, resp, data) =>{ +$.log(data) + let result = JSON.parse(data); + $.log(queryTime+"期账单明细:") + $.desc += queryTime+"期账单明细:\n" +return + try { + billDate = result.BILLINGCYCLE, + userName = result.customerName, + cashTotal = result.TOTAL / 100, + discount = result.CHARGEFREEDISCOUNT / 100, + mustPay = result.CHARGECORPUSDISCOUNT / 100; + for (lists of result.RESULTDATASET) { + billName = lists.CHARGETYPENAME, + billCharge = lists.CHARGE / 100; + $.desc += " "+billName + " 费用 " + billCharge + "元\n" + $.log(" "+billName + " 费用 " + billCharge + "元") + } + } catch(e) { + $.log("获取账单明细失败" + $.log(JSON.stringify(result, null, 2))) + } finally { + resolve() + } + }) + }) +} + +function queryBalance() { + return new Promise((resolve) =>{ + $.post(config('queryPhoneBalance'), (error, resp, data) =>{ + let result = JSON.parse(data); + try { + addressCity = result.CITYNAME, + teleNO = result.PRODUCTNO, + teleNO = teleNO.substr(0,3)+"****"+teleNO.substr(7) + balance = result.TELEBALANCE / 100, + userBalance = result.USAGEAMOUNT, + payAmount = result.payAmount / 100, + comBalance = result.COMBALANCE / 100; + if (balance < cash) { + $.msg($.name, "您的号码: " + teleNO + " 余额为" + balance + "元", "余额小于" + cash + "元,请您及时充值") + } + $.sub = "归属地:"+addressCity+" 号码:"+teleNO+" 余额:"+balance+"元" + } catch(e) { + $.log("获取手机余额失败" + $.log(JSON.stringify(result, null, 2))) + } finally { + resolve() + } + }) + }) +} + +function formatFlow(number) { + if (parseInt(number) < 1024) { + return number + "MB" + } + return (number/1024).toFixed(2) + "GB" +} + + +function Env(name,opts){class Http{constructor(env){this.env=env};send(opts,method='GET'){opts=typeof opts==='string'?{url:opts}:opts;let sender=this.get;if(method==='POST'){sender=this.post};return new Promise((resolve,reject)=>{sender.call(this,opts,(err,resp,body)=>{if(err)reject(err);else resolve(resp)})})};get(opts){return this.send.call(this.env,opts)};post(opts){return this.send.call(this.env,opts,'POST')}};return new(class{constructor(name,opts){this.name=name,this.http=new Http(this),this.data=null,this.dataFile='box.dat',this.logs=[],this.isMute=false,this.isNeedRewrite=false,this.logSeparator='\n';this.startTime=new Date().getTime();Object.assign(this,opts);this.log('',`🔔${this.name}, 开始!`)};isNode(){return'undefined'!==typeof module&&!!module.exports};isQuanX(){return'undefined'!==typeof $task};isSurge(){return'undefined'!==typeof $httpClient&&'undefined'===typeof $loon};isLoon(){return'undefined'!==typeof $loon};toObj(str,defaultValue=null){try{return JSON.parse(str)}catch{return defaultValue}};toStr(obj,defaultValue=null){try{return JSON.stringify(obj)}catch{return defaultValue}};getjson(key,defaultValue){let json=defaultValue;const val=this.getdata(key);if(val){try{json=JSON.parse(this.getdata(key))}catch{}};return json};setjson(val,key){try{return this.setdata(JSON.stringify(val),key)}catch{return false}}; getScript(url){return new Promise((resolve)=>{this.get({url},(err,resp,body)=>resolve(body))})};runScript(script,runOpts){return new Promise((resolve)=>{let httpapi=this.getdata('@chavy_boxjs_userCfgs.httpapi');httpapi=httpapi?httpapi.replace(/\n/g,'').trim():httpapi;let httpapi_timeout=this.getdata('@chavy_boxjs_userCfgs.httpapi_timeout');httpapi_timeout=httpapi_timeout?httpapi_timeout*1:20;httpapi_timeout=runOpts&&runOpts.timeout?runOpts.timeout:httpapi_timeout;const[key,addr]=httpapi.split('@');const opts={url:`http://${addr}/v1/scripting/evaluate`,body:{script_text:script,mock_type:'cron',timeout:httpapi_timeout},headers:{'X-Key':key,'Accept':'*/*'}};this.post(opts,(err,resp,body)=>resolve(body))}).catch((e)=>this.logErr(e))};loaddata(){if(this.isNode()){this.fs=this.fs?this.fs:require('fs');this.path=this.path?this.path:require('path');const curDirDataFilePath=this.path.resolve(this.dataFile);const rootDirDataFilePath=this.path.resolve(process.cwd(),this.dataFile);const isCurDirDataFile=this.fs.existsSync(curDirDataFilePath);const isRootDirDataFile=!isCurDirDataFile&&this.fs.existsSync(rootDirDataFilePath);if(isCurDirDataFile||isRootDirDataFile){const datPath=isCurDirDataFile?curDirDataFilePath:rootDirDataFilePath;try{return JSON.parse(this.fs.readFileSync(datPath))}catch(e){return{}}}else return{}}else return{}};writedata(){if(this.isNode()){this.fs=this.fs?this.fs:require('fs');this.path=this.path?this.path:require('path');const curDirDataFilePath=this.path.resolve(this.dataFile);const rootDirDataFilePath=this.path.resolve(process.cwd(),this.dataFile);const isCurDirDataFile=this.fs.existsSync(curDirDataFilePath);const isRootDirDataFile=!isCurDirDataFile&&this.fs.existsSync(rootDirDataFilePath);const jsondata=JSON.stringify(this.data);if(isCurDirDataFile){this.fs.writeFileSync(curDirDataFilePath,jsondata)}else if(isRootDirDataFile){this.fs.writeFileSync(rootDirDataFilePath,jsondata)}else{this.fs.writeFileSync(curDirDataFilePath,jsondata)}}};lodash_get(source,path,defaultValue=undefined){const paths=path.replace(/\[(\d+)\]/g,'.$1').split('.');let result=source;for(const p of paths){result=Object(result)[p];if(result===undefined){return defaultValue}};return result};lodash_set(obj,path,value){if(Object(obj)!==obj)return obj;if(!Array.isArray(path))path=path.toString().match(/[^.[\]]+/g)||[];path.slice(0,-1).reduce((a,c,i)=>(Object(a[c])===a[c]?a[c]:(a[c]=Math.abs(path[i+1])>>0===+path[i+1]?[]:{})),obj)[path[path.length-1]]=value;return obj};getdata(key){let val=this.getval(key);if(/^@/.test(key)){const[,objkey,paths]=/^@(.*?)\.(.*?)$/.exec(key);const objval=objkey?this.getval(objkey):'';if(objval){try{const objedval=JSON.parse(objval);val=objedval?this.lodash_get(objedval,paths,''):val}catch(e){val=''}}};return val};setdata(val,key){let issuc=false;if(/^@/.test(key)){const[,objkey,paths]=/^@(.*?)\.(.*?)$/.exec(key);const objdat=this.getval(objkey);const objval=objkey?(objdat==='null'?null:objdat||'{}'):'{}';try{const objedval=JSON.parse(objval);this.lodash_set(objedval,paths,val);issuc=this.setval(JSON.stringify(objedval),objkey)}catch(e){const objedval={};this.lodash_set(objedval,paths,val);issuc=this.setval(JSON.stringify(objedval),objkey)}}else{issuc=this.setval(val,key)};return issuc};getval(key){if(this.isSurge()||this.isLoon()){return $persistentStore.read(key)}else if(this.isQuanX()){return $prefs.valueForKey(key)}else if(this.isNode()){this.data=this.loaddata();return this.data[key]}else{return(this.data&&this.data[key])||null}};setval(val,key){if(this.isSurge()||this.isLoon()){return $persistentStore.write(val,key)}else if(this.isQuanX()){return $prefs.setValueForKey(val,key)}else if(this.isNode()){this.data=this.loaddata(),this.data[key]=val,this.writedata();return true}else{return(this.data&&this.data[key])||null}};initGotEnv(opts){this.got=this.got?this.got:require('got');this.cktough=this.cktough?this.cktough:require('tough-cookie');this.ckjar=this.ckjar?this.ckjar:new this.cktough.CookieJar();if(opts){opts.headers=opts.headers?opts.headers:{};if(undefined===opts.headers.Cookie&&undefined===opts.cookieJar){opts.cookieJar=this.ckjar}}}; get(opts,callback=()=>{}){if(opts.headers){delete opts.headers['Content-Type'];delete opts.headers['Content-Length']};if(this.isSurge()||this.isLoon()){if(this.isSurge()&&this.isNeedRewrite){opts.headers=opts.headers||{};Object.assign(opts.headers,{'X-Surge-Skip-Scripting':false})};$httpClient.get(opts,(err,resp,body)=>{if(!err&&resp){resp.body=body,resp.statusCode=resp.status};callback(err,resp,body)})}else if(this.isQuanX()){if(this.isNeedRewrite){opts.opts=opts.opts||{};Object.assign(opts.opts,{hints:false})};$task.fetch(opts).then((resp)=>{const{statusCode:status,statusCode,headers,body}=resp;callback(null,{status,statusCode,headers,body},body)},(err)=>callback(err))}else if(this.isNode()){this.initGotEnv(opts);this.got(opts).on('redirect',(resp,nextOpts)=>{try{if(resp.headers['set-cookie']){const ck=resp.headers['set-cookie'].map(this.cktough.Cookie.parse).toString();if(ck){this.ckjar.setCookieSync(ck,null)};nextOpts.cookieJar=this.ckjar}}catch(e){this.logErr(e)}}).then((resp)=>{const{statusCode:status,statusCode,headers,body}=resp;callback(null,{status,statusCode,headers,body},body)},(err)=>{const{message:error,response:resp}=err;callback(error,resp,resp&&resp.body)})}};post(opts,callback=()=>{}){if(opts.body&&opts.headers&&!opts.headers['Content-Type']){opts.headers['Content-Type']='application/x-www-form-urlencoded'};if(opts.headers)delete opts.headers['Content-Length'];if(this.isSurge()||this.isLoon()){if(this.isSurge()&&this.isNeedRewrite){opts.headers=opts.headers||{};Object.assign(opts.headers,{'X-Surge-Skip-Scripting':false})};$httpClient.post(opts,(err,resp,body)=>{if(!err&&resp){resp.body=body,resp.statusCode=resp.status};callback(err,resp,body)})}else if(this.isQuanX()){opts.method='POST';if(this.isNeedRewrite){opts.opts=opts.opts||{};Object.assign(opts.opts,{hints:false})};$task.fetch(opts).then((resp)=>{const{statusCode:status,statusCode,headers,body}=resp;callback(null,{status,statusCode,headers,body},body)},(err)=>callback(err))}else if(this.isNode()){this.initGotEnv(opts);const{url,..._opts}=opts;this.got.post(url,_opts).then((resp)=>{const{statusCode:status,statusCode,headers,body}=resp;callback(null,{status,statusCode,headers,body},body)},(err)=>{const{message:error,response:resp}=err;callback(error,resp,resp&&resp.body)})}};time(fmt,ts=null){const date=ts?new Date(ts):new Date();var o={"M+":date.getMonth()+1,"d+":date.getDate(),"h":date.getHours()%12==0?12:date.getHours()/12<1?"上午"+date.getHours()%12:"下午"+date.getHours()%12,"H+":date.getHours(),"m+":date.getMinutes(),"s+":date.getSeconds(),"q+":Math.floor((date.getMonth()+3)/3),"S":date.getMilliseconds()};var week={"0":"\u65e5","1":"\u4e00","2":"\u4e8c","3":"\u4e09","4":"\u56db","5":"\u4e94","6":"\u516d"};if(/(y+)/.test(fmt)){fmt=fmt.replace(RegExp.$1,(date.getFullYear()+"").substr(4-RegExp.$1.length))};if(/(E+)/.test(fmt)){fmt=fmt.replace(RegExp.$1,((RegExp.$1.length>1)?(RegExp.$1.length>2?"\u661f\u671f":"\u5468"):"")+week[date.getDay()+""])};for(var k in o){if(new RegExp("("+k+")").test(fmt)){fmt=fmt.replace(RegExp.$1,(RegExp.$1.length==1)?(o[k]):(("00"+o[k]).substr((""+o[k]).length)))}};return fmt};msg(title=name,subt='',desc='',opts){const toEnvOpts=(rawopts)=>{if(!rawopts)return rawopts;if(typeof rawopts==='string'){if(this.isLoon())return rawopts;else if(this.isQuanX())return{'open-url':rawopts};else if(this.isSurge())return{url:rawopts};else return undefined}else if(typeof rawopts==='object'){if(this.isLoon()){let openUrl=rawopts.openUrl||rawopts.url||rawopts['open-url'];let mediaUrl=rawopts.mediaUrl||rawopts['media-url'];return{openUrl,mediaUrl}}else if(this.isQuanX()){let openUrl=rawopts['open-url']||rawopts.url||rawopts.openUrl;let mediaUrl=rawopts['media-url']||rawopts.mediaUrl;return{'open-url':openUrl,'media-url':mediaUrl}}else if(this.isSurge()){let openUrl=rawopts.url||rawopts.openUrl||rawopts['open-url'];return{url:openUrl}}}else{return undefined}};if(!this.isMute){if(this.isSurge()||this.isLoon()){$notification.post(title,subt,desc,toEnvOpts(opts))}else if(this.isQuanX()){$notify(title,subt,desc,toEnvOpts(opts))}};if(!this.isMuteLog){let logs=['','==============📣\u7CFB\u7EDF\u901A\u77E5📣=============='];logs.push(title);subt?logs.push(subt):'';desc?logs.push(desc):'';console.log(logs.join('\n'));this.logs=this.logs.concat(logs)}};log(...logs){if(logs.length>0){this.logs=[...this.logs,...logs]};console.log(logs.join(this.logSeparator))};logErr(err,msg){const isPrintSack=!this.isSurge()&&!this.isQuanX()&&!this.isLoon();if(!isPrintSack){this.log('',`❗️${this.name}, \u9519\u8BEF!`,err)}else{this.log('',`❗️${this.name}, \u9519\u8BEF!`,err.stack)}};wait(time){return new Promise((resolve)=>setTimeout(resolve,time))};done(val={}){const endTime=new Date().getTime();const costTime=(endTime-this.startTime)/1000;this.log('',`🔔${this.name}, \u7ED3\u675F! 🕛 ${costTime} \u79D2`);this.log();if(this.isSurge()||this.isQuanX()||this.isLoon()){$done(val)}}})(name,opts)} diff --git a/Task/baidu_speed.js b/Task/baidu_speed.js new file mode 100644 index 0000000000..f55e4a5e97 --- /dev/null +++ b/Task/baidu_speed.js @@ -0,0 +1,560 @@ +/* +更新时间:2021-02-14 19:10 +百度极速版签到任务,使用脚本有黑号严重,请谨慎使用‼️ + +赞赏:百度极速邀请码`RW9ZSW 点击链接立得红包,最高100元!https://dwz.cn/Oilv4CJ1`,农妇山泉 -> 有点咸,万分感谢 + +本脚本默认使用chavyleung大佬和Nobyda的贴吧ck,获取方法请看大佬仓库说明,内置自动提现,提现金额默认30元,当当前时间为早上6点且达到提现金额时仅运行提现任务,提现金额小于设置金额时继续运行其他任务。 + +增加百度任务开关,Actions中Secrets为BAIDU_TASK,值填true或者false + +支持BoxJs多账号,需手动填写,用&或者换行隔开 + +~~~~~~~~~~~~~~~~ + +*/ +const $ = new Env('百度极速版') +let CookieArr = [],cashArr=[]; +const notify = $.isNode() ? require('./sendNotify') : ''; +const baiducks = $.getdata(`chavy_cookie_tieba`) || $.getdata(`CookieTB`); +let baiducash = $.getdata(`cash_baidu`); + +let taskON = $.getdata(`task_baidu`)||"true"//除提现和兑换外其他任务开关; +let isblack = "false"; +let UA = 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 SP-engine/2.24.0 matrixstyle/0 info baiduboxapp/5.1.6.10 (Baidu; P2 14.2)' + + +if(!$.isNode()&&baiducks && baiducks.indexOf('&')==-1){ + CookieArr.push(baiducks); + cashArr.push($.getdata("cash_baidu")||30) +} else { +if ($.isNode()) { + if (process.env.BAIDU_COOKIE && process.env.BAIDU_COOKIE.indexOf('&') > -1) { + BDCookie = process.env.BAIDU_COOKIE.split('&'); + } + else if (process.env.BAIDU_COOKIE && process.env.BAIDU_COOKIE.indexOf('\n') > -1) { + BDCookie = process.env.BAIDU_COOKIE.split('\n'); + } else { + BDCookie = process.env.BAIDU_COOKIE.split() + }; + if (process.env.BAIDU_CASH && process.env.BAIDU_CASH.indexOf('&') > -1) { + BDCASH = process.env.BAIDU_CASH.split('&'); + } + else if (process.env.BAIDU_CASH && process.env.BAIDU_CASH.indexOf('\n') > -1) { + BDCASH = process.env.BAIDU_CASH.split('\n'); + } else { + BDCASH = [process.env.BAIDU_CASH] + } +} else if (!$.isNode()&&baiducks && baiducks.indexOf('&')>-1){ + BDCookie = baiducks.split("&") + BDCASH = [baiducash] +} + + Object.keys(BDCookie).forEach((item) => { + if (BDCookie[item]) { + CookieArr.push(BDCookie[item]) + } + }); + Object.keys(BDCASH).forEach((item) => { + if (BDCASH[item]) { + cashArr.push(BDCASH[item]) + } + }) + console.log(`您共提供${CookieArr.length}个百度账号 Cookie`) + } + +!(async() =>{ + if (!CookieArr[0]) { + console.log($.name, '【提示】请把百度Cookie填入Github 的 Secrets 中,请以&或者换行隔开'); + return + }; + timeZone = new Date().getTimezoneOffset() / 60; + timestamp = Date.now()+ (8+timeZone) * 60 * 60 * 1000; + bjTime = new Date(timestamp).toLocaleString('zh',{hour12:false,timeZoneName: 'long'}); + console.log(`\n === 脚本执行 ${bjTime} ===\n`); + for (let i = 0; i < CookieArr.length; i++) { + if (CookieArr[i]) { + cookieval = CookieArr[i]; + withcash = cashArr[i]; + $.index = i + 1; + await userInfo(); + await $.wait(1000); + if ($.isNode()) { + if (process.env.BAIDU_TASK) { + taskON = process.env.BAIDU_TASK + } + } + if (taskON == "true") { + $.desc = ""; + await firstbox(); + await TaskCenter(); + } + } + } +})() + .catch((e) => $.logErr(e)) + .finally(() => $.done()) + +function confApi(api, body, RefererUrl) { + return { + url: 'https://haokan.baidu.com/activity/'+api, + headers:{ + 'Cookie': cookieval, + 'User-Agent': UA, + 'Referer': RefererUrl + }, + body:body + } +} +//签到 +function getsign() { + return new Promise((resolve, reject) =>{ + $.post(confApi('acusercheckin/update','productid=2&ugus=9766888061'), async(error, resp, data) =>{ + let get_sign = JSON.parse(data); + if (get_sign.errno == 0) { + $.desc = get_sign.data.tips+` 收益: ${get_sign.data.bonus.coin}💰\n`; + $.log($.desc+"\n"+data); + await invite() + } else { + $.sub = `签到失败❌`, + $.desc = `说明: ` + get_sign.msg+"\n", + $.msg($.name, $.sub, $.desc); + //$.done() + } + resolve() + }) + }) +} + +function withDraw(cash) { + return new Promise((resolve, reject) =>{ + $.get(confApi(`acuserwithdraw/confirm?productid=2&amount=${cash*100}&trade_type=1`), async(error, resp, data) =>{ + let get_cash = JSON.parse(data); + if (get_cash.errno == 0) { + $.sub = ' 提现成功: 到账 ' + get_cash.data.money + "元 "; + $.msg($.name, $.sub); + if ($.isNode()) { + await notify.sendNotify($.name + " 成功提现" + withcash + "元\n" + $.sub) + } + } else { + $.log(data + "\n " + get_cash.msg); + $.msg($.name, get_cash.msg) + } + resolve() + }) + }) +} + + +function invite() { + return new Promise((resolve, reject) =>{ + let inviteurl = { + url: `https://haokan.baidu.com/activity/h5/vault?productid=2&inviteCode=RW9ZSW&pkg=%5Bpkg%5D `, + headers: { + Cookie: cookieval + } + } + $.get(inviteurl, (error, resp, data) =>{ + if (error) { + //$.log("响应错误") + } + resolve() + }) + }) +} + +function userInfo() { + return new Promise((resolve, reject) =>{ + $.post(confApi('api/tenure/osname=baiduboxapp','sign=a329b14e561e5f42d466d568623cd972&time=1612958577&productid=2'), async(error, resp, data) =>{ + try { + let get_pay = JSON.parse(data); + //$.log("获取收益信息:"+data +'\n') + if (get_pay.errno == 0) { + availablecoin = get_pay.data.available_coin, + enabledcoin = get_pay.data.enabled_coin, + enabledmoney = get_pay.data.enabled_money, + yesterdaycoin = get_pay.data.yesterday_coin; + if(CookieArr.length==1){ + username = $.getdata('baidu_nick') ? $.getdata('baidu_nick') : null; + } else { + username = "账号"+ $.index + } + $.sub = " 昵称:" + username + " 现金:" + enabledmoney + "元 金币:" + availablecoin; + $.log("\n********** 昵称:" + username + " 现金:" + enabledmoney + "元 **********\n"); + if (parseInt(enabledmoney) >= Number(withcash) && $.time("HH") == "06") { + await withDraw(withcash); + $.done() + }; + if (enabledcoin > 100) { + coinnum = parseInt(enabledcoin / 100) * 100; + await coinexChange() + } + } + } catch(e) { + $.log("获取用户信息失败" + e) + } finally { + resolve() + } + }) + }) +} + +function coinexChange() { + return new Promise((resolve, reject) =>{ + $.get(confApi(`api/coinexchange?coinnum=${coinnum}&autolock=1&productid=2&ugVersion=5.1.6.10`), (error, resp, data) =>{ + let exchange = JSON.parse(data) + //$.log(data) + if (exchange.errno == 0) { + $.log("兑换成功,"+ exchange.data.message) + $.msg($.name, "金币兑换成功,"+ exchange.data.message) + } + resolve() + }) + }) +} + +function TaskCenter() { + return new Promise((resolve, reject) =>{ + $.get(confApi('h5/vaultnew?productid=2&fromcsr=1&system=ios&_format=json'), async(error, resp, data) =>{ + try { + let get_tasks = JSON.parse(data); + if(get_tasks.errno==7){ + $.msg($.name, get_tasks.msg, "请更换Cookie后,重试"); + return + } else if(get_tasks.data.uname!=""&&CookieArr.length==1){ + username = get_tasks.data.uname; + $.setdata(username,'baidu_nick') + } + isblack = get_tasks.data.is_black + + $.log(" 🛎 ========== 任务开始 ========== 🛎 "); + tasks = get_tasks.data.comps; + for (x in tasks) { + if (isblack == true) { + $.msg($.name + " 账号" + username + "已黑号", "您的金币和余额已被冻结,请联系客服处理"); + break; + } + taskid = tasks[x].taskId; + id = tasks[x].id; + if (tasks[x].name == "signIn") { + for (z in tasks[x].data.checkin_list) { + signs = tasks[x].data.checkin_list + if (tasks[x].data.current_date == signs[z].date) { + if (signs[z].is_checkin == 0) { + await getsign() + } else { + $.desc = "【签到结果】✅ 今日+" + signs[z].coin_reward + "金币\n"; + $.log($.desc) + } + } + } + } else { + await getConfigs() + } + } + } catch(e) { + $.logErr(e, data); + } finally { + $.msg($.name, $.sub, $.desc) + resolve() + } + }) + }) +} + +async function getConfigs() { + if (tasks[x].name == "taskList") { + maxTitle = tasks[x].data.title; + $.log("\n去" + maxTitle); + if (maxTitle == "玩游戏赚现金") { + //$.log(JSON.stringify(tasks[x].data)) + } else { + for (arr of tasks[x].data.tasklist) { + taskName = "【" + arr.title + "】"; + tid = arr.id; + taskType = arr.type; + if (arr.taskStatus == "1") { + $.log(taskName + " 已完成\n"); + $.desc += taskName + "✅ 已完成\n"; + } else if (taskType == 'openApp') { + RefererUrl = arr.adLink; + $.log("\n"+taskName+" 类型: "+arr.type_name+" ") + if( tid =="815"){ + RefererUrl="https://eopa.baidu.com/page/pagekey-ASKWNd8W?productid=2&type=1&tid=815" + } + await activeBox() + } else if (taskType == 'watch') { + tips = arr.tips; + count = arr.total_count; + $.log("\n"+taskName + tips + "总计" + count + "次 "); + if (arr.taskStatus == 0&&$.desc.indexOf("【签到结果】✅")>-1) { + await $.wait(2000); + await get_search("184") + } + $.desc += taskName + tips + "总计" + count + "次\n"; + }; + } + } + } + if (tasks[x].name == "popularRecommendation") { + //$.log(tasks[x].data.recommendCompName) + } + if (id == "1068") { + if (tasks[x].data.unOpenHeadBoxDialog.isShowBusiness == true ){ + tid = "817" + taskName = "【"+tasks[x].data.unOpenHeadBoxDialog.btn[0].btnText+"】" + RefererUrl = tasks[x].data.unOpenHeadBoxDialog.btn[0].iosAdUrl + $.log("\n"+taskName+" ") + await activeBox() +} + if (tasks[x].data.gameheader.coinInfo.coinStatus == 2) { + $.desc += "\n【头部宝箱】✅ 总计金币" + tasks[x].data.gameheader.coinInfo.coinCount + "\n"; + $.log($.desc) + } else { + for (headerbox of tasks[x].data.gameheader.progressList) { + if (headerbox.status == 1) { + await $.wait(2000); + await headerBox() + } + } + }; + for ( jingangs of tasks[x].data.jingang.list){ + jingangType = jingangs.jingangType, + taskName = "【"+jingangs.jingangName+"】 ", + RefererUrl = jingangs.jingangUrl, + tid = jingangs.jingangTid; + if (jingangType == 2) { + if (tasks[x].data.jingang.countDown[tid].countDown == 0) { + await $.wait(1000); + $.log("\n"+taskName+" "); + await activeBox(); + } else { + $.log("\n"+taskName+ " 请等待" +Number(tasks[x].data.jingang.countDown[tid].countDown / 60).toFixed(2) + "分钟") + } + } + } + } +} + + +//首页宝箱 +function firstbox() { + return new Promise((resolve, reject) =>{ + let bdurl = { + url: 'https://mbrowser.baidu.com/lite/gold/receive?service=bdbox', + headers: { + "Cookie": cookieval, + "User-Agent": UA + }, + body: 'task_type=-1&task_id=-1' + } + $.post(bdurl, (error, resp, data) =>{ + let get_first = JSON.parse(data) + //$.log("获取首页宝箱信息:"+data +'\n') + if (get_first.err_no == 0) { + $.desc += "【首页宝箱】" + get_first.data.result.tips + ", " + get_first.data.result.countdown_time + "秒后再次开启宝箱\n" + } else if (get_first.err_no == 10079) { + $.desc += "【首页宝箱】✅ " + get_first.tip + '\n' + } else if (get_first.err_no == 10060) { + $.log("首页宝箱开启失败"+get_first.tip+"\n") + } + resolve() + }) + }) +} + +function activeBox() { + return new Promise((resolve, reject) =>{ + let actboxurl = { + url: `https://haokan.baidu.com/activity/tasks/active?productid=2&id=${tid}`, + headers: { + Cookie: cookieval, + 'User-Agent': UA, + Referer: RefererUrl + } + } + $.get(actboxurl, async(error, resp, data)=>{ + try{ + let act_box = JSON.parse(data); + if ((tid == 587 || tid == 590) && act_box.errno == 0) { + await get_pkg() + } else if (act_box.errno == 1){ + $.desc+= "【taskName】"+ act_box.msg+"\n"; + $.log(act_box.msg+",请检查Cookie是否包含BAIDUCUID;\n"); + return + } else if (data.indexOf("EquipmentComplete") >-1) { + $.log(act_box.data.data+"\n") + } else { + await get_pkg() + } + } catch(e) { + $.logErr(e, data); + } finally { + resolve() + } + }) + }) +} + +//视频 +function get_pkg() { + return new Promise((resolve, reject) =>{ + let pkgurl = { + url: `https://haokan.baidu.com/activity/acad/rewardad?device=%7B%22imei_md5%22%3A%22%22%2C%22device_type%22%3A1%2C%22model%22%3A%22IPHONE%22%2C%22manufacturer%22%3A%22Apple%22%2C%22os_version%22%3A%2213.7%22%2C%22idfa%22%3A%22_a2S8_aq28_qa28qii2A8laJ28gxC28Q_iXni0uKvNYIPviVzaHtiYah2ul6iHim_l2880uQvflqisa9liBgIgarv8oIOHutlhSPu_ux2a_Wi-uRz_qAC%22%7D&network=%7B%22connect_type%22%3A1%2C%22carrier%22%3A0%7D&productid=2&tid=${tid}&type=1`, + headers: { + Cookie: cookieval, + 'User-Agent': UA, + 'Referer': RefererUrl + } + } + $.get(pkgurl, async(error, resp, data) =>{ + let get_pkg = JSON.parse(data); + if (get_pkg.errno == 0 && get_pkg.data.isDone == 0) { + Pkg = get_pkg.data.adInfo[0].material.pkg, + taskid = get_pkg.data.taskPf.taskId; + $.log(" 获取任务成功,等待25s获取收益"); + //$.log("\n" + taskid + " " + Pkg); + await $.wait(25000); + await finishTask() + } else if (get_pkg.errno == 0 && get_pkg.data.isDone == 1) { + // $.desc += taskName + "✅ 已完成\n"; + // $.log(taskName + "已完成\n") + } + resolve() + }) + }) +} + +function finishTask() { + return new Promise((resolve, reject) =>{ + let actboxurl = { + url: `https://eopa.baidu.com/api/task/1/task/${taskid}/complete?rewardType=coin&rewardVideoPkg=${Pkg}&sys=ios`, + headers: { + Cookie: cookieval, + 'User-Agent': UA, + Referer: RefererUrl + } + } + $.get(actboxurl, async(error, resp, data) =>{ + try { + let do_task = JSON.parse(data); + if (do_task.errno == 0) { + $.desc += taskName + "获得收益" + do_task.data.coin + "\n"; + $.log(taskName + " 获得收益: +" + do_task.data.coin); + await $.wait(1000) + } else if (do_task.errno == 19001) { + $.desc += taskName + " " + do_task.errmsg + "\n"; + $.log(taskName + " " + do_task.errmsg) + } else if (do_task.errno == 11004) { + $.desc += taskName + " " + do_task.errmsg + "\n"; + $.log(taskName + " " + do_task.errmsg) + } + } catch(e) { + $.logErr(e+data); + } finally { + resolve() + } + }) + }) +} + + +function get_search(cmd) { + return new Promise((resolve) =>{ + let geturl = { + url: `https://mbd.baidu.com/searchbox?action=feed&cmd=${cmd}&network=1_0&osbranch=i3&osname=baiduboxapp&uid=A49D6DBEA0E8C89406AD1484C84D9134FCF6C8758FHLNHLAJSR&ut=iPhone10%2C1_14.2&ua=1242_2208_iphone_5.0.0.11_0&fv=12.1.0.0`, + headers: { + Cookie: cookieval, + 'User-Agent': UA + } + } + $.get(geturl, async(error, resp, data) =>{ + try { + $.log(" tid:" + tid + " 状态码:" + resp.statusCode); + let get_search = JSON.parse(data); + if (get_search.errno == 0) { + for (items of get_search.data[`${cmd}`].itemlist.items) { + searchId = items.id, + searchname = items.data.title; + author = items.data.author + if (items.data.mode == "video" || items.data.type == "video") { + $.log(" 观看视频: " + searchname + " ------------ " + author); + } + else if (items.data.mode == "text") { + $.log(" 阅读短文: " + searchname + "\n " + " ------------ " + items.data.tag ? items.data.tag: ""); + } + else if (items.data.mode == "ad") { + $.log(" 打开广告: " + author + ": " + searchname); + } + if (typeof coin == "undefined") { + $.log(" 请等待,30s后获取收益\n"); + await $.wait(30000); + await searchBox(searchId) + } else if (coin == 0) { + $.log(" 请等待5s获取收益\n"); + await $.wait(5000); + await searchBox(searchId) + coin = "undefined"; + } else if (coin == 3) { + $.log(" 金币为3时,跳出运行\n"); + await $.wait(2000) + coin = "undefined"; + break + } else { + $.log(" 请等待,30s后获取收益\n"); + await $.wait(30000); + await searchBox(searchId) + } + //totalcoin += coin + //$.log(totalcoin) + } + //$.desc += taskName + "获得收益"+ totalcoin+ "金币" +coin + "\n" + } + } catch(error) { + $.logErr(error + data); + } finally { + resolve() + } + }) + }) +} + +function searchBox(id) { + return new Promise((resolve) =>{ + let searchurl = { + url: `https://mbd.baidu.com/searchbox?action=feed&cmd=197&imgtype=webp&network=1_0&osbranch=i3&osname=baiduboxapp&ua=1242_2208_iphone_5.0.0.11_0&uid=A49D6DBEA0E8C89406AD1484C84D9134FCF6C8758FHLNHLAJSR&ut=iPhone10%2C1_14.2`, + headers: {"Cookie":cookieval,'User-Agent': UA}, + body: `data={"origin_nid":"${id}","taskid":"${tid}"}` + }; + $.post(searchurl, async(error, resp, data) =>{ + //$.log(error + resp.statusCode+" "+data) + try{ + let do_search = JSON.parse(data); + if (do_search.errno == 0 && do_search.data['197'].istip == 1) { + $.log(" 获得收益: " + do_search.data[`197`].tips+"😜\n"); + coin = Number(do_search.data[`197`].righttips) + //totalcoin = += coin + await $.wait(1000) + } else if (do_search.data[`197`].tips == "") { + coin = 0; + $.log(" 对不起,本次没有收益🥺\n"); + } else { + $.log("获得收益失败,"+do_search.data[`197`].tips) + } + }catch(e) { + $.logErr(e+data); + } finally { + resolve(coin) + } + }) + }) +} + +function showmsg() { + + $.msg($.name,$.sub,$.desc) + +} + + +function Env(t,e){class s{constructor(t){this.env=t}send(t,e="GET"){t="string"==typeof t?{url:t}:t;let s=this.get;return"POST"===e&&(s=this.post),new Promise((e,i)=>{s.call(this,t,(t,s,r)=>{t?i(t):e(s)})})}get(t){return this.send.call(this.env,t)}post(t){return this.send.call(this.env,t,"POST")}}return new class{constructor(t,e){this.name=t,this.http=new s(this),this.data=null,this.dataFile="box.dat",this.logs=[],this.isMute=!1,this.isNeedRewrite=!1,this.logSeparator="\n",this.startTime=(new Date).getTime(),Object.assign(this,e),this.log("",`\ud83d\udd14${this.name}, \u5f00\u59cb!`)}isNode(){return"undefined"!=typeof module&&!!module.exports}isQuanX(){return"undefined"!=typeof $task}isSurge(){return"undefined"!=typeof $httpClient&&"undefined"==typeof $loon}isLoon(){return"undefined"!=typeof $loon}toObj(t,e=null){try{return JSON.parse(t)}catch{return e}}toStr(t,e=null){try{return JSON.stringify(t)}catch{return e}}getjson(t,e){let s=e;const i=this.getdata(t);if(i)try{s=JSON.parse(this.getdata(t))}catch{}return s}setjson(t,e){try{return this.setdata(JSON.stringify(t),e)}catch{return!1}}getScript(t){return new Promise(e=>{this.get({url:t},(t,s,i)=>e(i))})}runScript(t,e){return new Promise(s=>{let i=this.getdata("@chavy_boxjs_userCfgs.httpapi");i=i?i.replace(/\n/g,"").trim():i;let r=this.getdata("@chavy_boxjs_userCfgs.httpapi_timeout");r=r?1*r:20,r=e&&e.timeout?e.timeout:r;const[o,h]=i.split("@"),a={url:`http://${h}/v1/scripting/evaluate`,body:{script_text:t,mock_type:"cron",timeout:r},headers:{"X-Key":o,Accept:"*/*"}};this.post(a,(t,e,i)=>s(i))}).catch(t=>this.logErr(t))}loaddata(){if(!this.isNode())return{};{this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(this.dataFile),e=this.path.resolve(process.cwd(),this.dataFile),s=this.fs.existsSync(t),i=!s&&this.fs.existsSync(e);if(!s&&!i)return{};{const i=s?t:e;try{return JSON.parse(this.fs.readFileSync(i))}catch(t){return{}}}}}writedata(){if(this.isNode()){this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(this.dataFile),e=this.path.resolve(process.cwd(),this.dataFile),s=this.fs.existsSync(t),i=!s&&this.fs.existsSync(e),r=JSON.stringify(this.data);s?this.fs.writeFileSync(t,r):i?this.fs.writeFileSync(e,r):this.fs.writeFileSync(t,r)}}lodash_get(t,e,s){const i=e.replace(/\[(\d+)\]/g,".$1").split(".");let r=t;for(const t of i)if(r=Object(r)[t],void 0===r)return s;return r}lodash_set(t,e,s){return Object(t)!==t?t:(Array.isArray(e)||(e=e.toString().match(/[^.[\]]+/g)||[]),e.slice(0,-1).reduce((t,s,i)=>Object(t[s])===t[s]?t[s]:t[s]=Math.abs(e[i+1])>>0==+e[i+1]?[]:{},t)[e[e.length-1]]=s,t)}getdata(t){let e=this.getval(t);if(/^@/.test(t)){const[,s,i]=/^@(.*?)\.(.*?)$/.exec(t),r=s?this.getval(s):"";if(r)try{const t=JSON.parse(r);e=t?this.lodash_get(t,i,""):e}catch(t){e=""}}return e}setdata(t,e){let s=!1;if(/^@/.test(e)){const[,i,r]=/^@(.*?)\.(.*?)$/.exec(e),o=this.getval(i),h=i?"null"===o?null:o||"{}":"{}";try{const e=JSON.parse(h);this.lodash_set(e,r,t),s=this.setval(JSON.stringify(e),i)}catch(e){const o={};this.lodash_set(o,r,t),s=this.setval(JSON.stringify(o),i)}}else s=this.setval(t,e);return s}getval(t){return this.isSurge()||this.isLoon()?$persistentStore.read(t):this.isQuanX()?$prefs.valueForKey(t):this.isNode()?(this.data=this.loaddata(),this.data[t]):this.data&&this.data[t]||null}setval(t,e){return this.isSurge()||this.isLoon()?$persistentStore.write(t,e):this.isQuanX()?$prefs.setValueForKey(t,e):this.isNode()?(this.data=this.loaddata(),this.data[e]=t,this.writedata(),!0):this.data&&this.data[e]||null}initGotEnv(t){this.got=this.got?this.got:require("got"),this.cktough=this.cktough?this.cktough:require("tough-cookie"),this.ckjar=this.ckjar?this.ckjar:new this.cktough.CookieJar,t&&(t.headers=t.headers?t.headers:{},void 0===t.headers.Cookie&&void 0===t.cookieJar&&(t.cookieJar=this.ckjar))}get(t,e=(()=>{})){t.headers&&(delete t.headers["Content-Type"],delete t.headers["Content-Length"]),this.isSurge()||this.isLoon()?(this.isSurge()&&this.isNeedRewrite&&(t.headers=t.headers||{},Object.assign(t.headers,{"X-Surge-Skip-Scripting":!1})),$httpClient.get(t,(t,s,i)=>{!t&&s&&(s.body=i,s.statusCode=s.status),e(t,s,i)})):this.isQuanX()?(this.isNeedRewrite&&(t.opts=t.opts||{},Object.assign(t.opts,{hints:!1})),$task.fetch(t).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>e(t))):this.isNode()&&(this.initGotEnv(t),this.got(t).on("redirect",(t,e)=>{try{if(t.headers["set-cookie"]){const s=t.headers["set-cookie"].map(this.cktough.Cookie.parse).toString();s&&this.ckjar.setCookieSync(s,null),e.cookieJar=this.ckjar}}catch(t){this.logErr(t)}}).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>{const{message:s,response:i}=t;e(s,i,i&&i.body)}))}post(t,e=(()=>{})){if(t.body&&t.headers&&!t.headers["Content-Type"]&&(t.headers["Content-Type"]="application/x-www-form-urlencoded"),t.headers&&delete t.headers["Content-Length"],this.isSurge()||this.isLoon())this.isSurge()&&this.isNeedRewrite&&(t.headers=t.headers||{},Object.assign(t.headers,{"X-Surge-Skip-Scripting":!1})),$httpClient.post(t,(t,s,i)=>{!t&&s&&(s.body=i,s.statusCode=s.status),e(t,s,i)});else if(this.isQuanX())t.method="POST",this.isNeedRewrite&&(t.opts=t.opts||{},Object.assign(t.opts,{hints:!1})),$task.fetch(t).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>e(t));else if(this.isNode()){this.initGotEnv(t);const{url:s,...i}=t;this.got.post(s,i).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>{const{message:s,response:i}=t;e(s,i,i&&i.body)})}}time(t){let e={"M+":(new Date).getMonth()+1,"d+":(new Date).getDate(),"H+":(new Date).getHours(),"m+":(new Date).getMinutes(),"s+":(new Date).getSeconds(),"q+":Math.floor(((new Date).getMonth()+3)/3),S:(new Date).getMilliseconds()};/(y+)/.test(t)&&(t=t.replace(RegExp.$1,((new Date).getFullYear()+"").substr(4-RegExp.$1.length)));for(let s in e)new RegExp("("+s+")").test(t)&&(t=t.replace(RegExp.$1,1==RegExp.$1.length?e[s]:("00"+e[s]).substr((""+e[s]).length)));return t}msg(e=t,s="",i="",r){const o=t=>{if(!t)return t;if("string"==typeof t)return this.isLoon()?t:this.isQuanX()?{"open-url":t}:this.isSurge()?{url:t}:void 0;if("object"==typeof t){if(this.isLoon()){let e=t.openUrl||t.url||t["open-url"],s=t.mediaUrl||t["media-url"];return{openUrl:e,mediaUrl:s}}if(this.isQuanX()){let e=t["open-url"]||t.url||t.openUrl,s=t["media-url"]||t.mediaUrl;return{"open-url":e,"media-url":s}}if(this.isSurge()){let e=t.url||t.openUrl||t["open-url"];return{url:e}}}};if(this.isMute||(this.isSurge()||this.isLoon()?$notification.post(e,s,i,o(r)):this.isQuanX()&&$notify(e,s,i,o(r))),!this.isMuteLog){let t=["","==============\ud83d\udce3\u7cfb\u7edf\u901a\u77e5\ud83d\udce3=============="];t.push(e),s&&t.push(s),i&&t.push(i),console.log(t.join("\n")),this.logs=this.logs.concat(t)}}log(...t){t.length>0&&(this.logs=[...this.logs,...t]),console.log(t.join(this.logSeparator))}logErr(t,e){const s=!this.isSurge()&&!this.isQuanX()&&!this.isLoon();s?this.log("",`\u2757\ufe0f${this.name}, \u9519\u8bef!`,t.stack):this.log("",`\u2757\ufe0f${this.name}, \u9519\u8bef!`,t)}wait(t){return new Promise(e=>setTimeout(e,t))}done(t={}){const e=(new Date).getTime(),s=(e-this.startTime)/1e3;this.log("",`\ud83d\udd14${this.name}, \u7ed3\u675f! \ud83d\udd5b ${s} \u79d2`),this.log(),(this.isSurge()||this.isQuanX()||this.isLoon())&&$done(t)}}(t,e)} diff --git a/Task/bestPay.js b/Task/bestPay.js new file mode 100644 index 0000000000..c357f14be9 --- /dev/null +++ b/Task/bestPay.js @@ -0,0 +1,175 @@ +/* +更新时间: 2021-02-20 20:50 +https:\/\/czapp\.bestpay\.com\.cn\/payassistant-client\?method=queryPhoneBalance url script-request-body bestPay.js +hostname = czapp.bestpay.com.cn +翼支付打开权益专区,点击套餐详情,重进翼支付App时需重新获取请求,即重写配置不必禁用 + +*/ +const $ = new Env('翼支付电信套餐'); +const bodyVal = $.getdata('bestpay_tele'); +const queryTime = $.getdata('bestpay_bill').replace("-","")||parseInt($.time("yyyyMM")-1); +const cash = $.getdata('tele_balance')||"10"; + +let isGetCookie = typeof $request !== 'undefined' +if (isGetCookie) { + GetCookie() +} else { +!(async () => { + await queryBalance(); + await queryResource(); + await queryBill(); + $.msg($.name,$.sub,$.desc) +})() + .catch((e) => $.logErr(e)) + .finally(() => $.done()) +} +function GetCookie() { + if ($request.body) { + var bodyValue = $request.body; + if ($.getdata('bestpay_tele') != (undefined || null)) { + if ($.getdata('bestpay_tele') != bodyValue) { + var bodys = $.setdata(bodyValue, 'bestpay_tele'); + if (!bodys) { + $.msg("更新" + $.name + "请求失败‼️", "", ""); + $.log(`获取请求体: 失败`); + } else { + $.msg("更新" + $.name + "请求成功 🎉", "", ""); + $.log($.name+`, 获取请求: 成功, body: ${bodyValue}`) + } + } + } else { + var bodys = $.setdata(bodyValue, 'bestpay_tele'); + if (!bodys) { + $.msg("首次写入" + $.name + "请求失败‼️", "", ""); + } else { + $.msg("首次写入" + $.name + "请求成功 🎉", "", ""); + } + } + } else { + $.msg("写入" + $.name + "请求失败‼️", "", "配置错误, 无法读取请求体, "); + } + $.done() +} + + +function config(api,queryApi) { + return { + url:'https://czapp.bestpay.com.cn/payassistant-client?method='+api, + headers:{ + Host: 'czapp.bestpay.com.cn', + Referer: 'https://h5.bestpay.com.cn/subapps/payassistant/payassistant-new/index.html?hybridVersion=3.0&channel=quanyi', + 'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 Bestpay/10.1.91 hybridVersion/3.0 /sa-sdk-ios', + 'Content-Type': 'application/x-www-form-urlencoded' + }, + body: bodyVal+"&"+queryApi + } +} + + +function queryResource() { + return new Promise((resolve) =>{ + $.post(config('queryUserResource', 'BILLCYCLE='+$.time("yyyyMM")), (error, resp, data) =>{ + let result = JSON.parse(data); + try { + if (result.RESPONSECODE == "000000") { + products = result.RESULTDATASET; + //$.log(JSON.stringify(products,null,2)); + $.desc = "使用详情:\n"; + $.log("已开套餐:") + for (x in products) { + productsname = products[x].PRODUCTOFFNAME, + offerType = products[x].OFFERTYPE, + ratableid = products[x].RATABLERESOURCEID; + $.log(" "+productsname+" 类型:"+offerType); + if (ratableid) { + unitType = products[x].UNITTYPEID, + ratableName = products[x].RATABLERESOURCENAME, + mainname = productsname, + ratableAmount = products[x].RATABLEAMOUNT, + balanceAmount = products[x].BALANCEAMOUNT, + usageAmount = products[x].USAGEAMOUNT; + if(unitType !== "KB") { + usageAmount += unitType, + ratableAmount += unitType , + balanceAmount += unitType + } else if (unitType == "KB") { + usageAmount = formatFlow(usageAmount), + ratableAmount = formatFlow(ratableAmount), + balanceAmount = formatFlow(balanceAmount); + ratableName = ratableName?ratableName:productsname; + } + $.desc += " "+ratableName +":"+(balanceAmount?"总计:"+ratableAmount+" 使用:"+usageAmount+" 剩余:"+balanceAmount+"\n":""); + } + } + $.log("\n"+$.desc) + } + } catch(e) { + $.log("查询套餐信息错误"+ $.log(JSON.stringify(result,null,2))) + } finally { + resolve() + } + }) + }) +} + +function queryBill() { + return new Promise((resolve) =>{ + $.post(config('detailBillQueryNew', 'BILLCYCLE=' + queryTime), (error, resp, data) =>{ + let result = JSON.parse(data); + $.log(queryTime+"期账单明细:") + $.desc += queryTime+"期账单明细:\n" + try { + billDate = result.BILLINGCYCLE, + userName = result.customerName, + cashTotal = result.TOTAL / 100, + discount = result.CHARGEFREEDISCOUNT / 100, + mustPay = result.CHARGECORPUSDISCOUNT / 100; + for (lists of result.RESULTDATASET) { + billName = lists.CHARGETYPENAME, + billCharge = lists.CHARGE / 100; + $.desc += " "+billName + " 费用 " + billCharge + "元\n" + $.log(" "+billName + " 费用 " + billCharge + "元") + } + } catch(e) { + $.log("获取账单明细失败" + $.log(JSON.stringify(result, null, 2))) + } finally { + resolve() + } + }) + }) +} + +function queryBalance() { + return new Promise((resolve) =>{ + $.post(config('queryPhoneBalance'), (error, resp, data) =>{ + let result = JSON.parse(data); + try { + addressCity = result.CITYNAME, + teleNO = result.PRODUCTNO, + teleNO = teleNO.substr(0,3)+"****"+teleNO.substr(7) + balance = result.TELEBALANCE / 100, + userBalance = result.USAGEAMOUNT, + payAmount = result.payAmount / 100, + comBalance = result.COMBALANCE / 100; + if (balance < cash) { + $.msg($.name, "您的号码: " + teleNO + " 余额为" + balance + "元", "余额小于" + cash + "元,请您及时充值") + } + $.sub = "归属地:"+addressCity+" 号码:"+teleNO+" 余额:"+balance+"元" + } catch(e) { + $.log("获取手机余额失败" + $.log(JSON.stringify(result, null, 2))) + } finally { + resolve() + } + }) + }) +} + +function formatFlow(number) { + if (number/1024 < 1024) { + return (number/1024).toFixed(2) + "MB" + } + return (number/1024/1024).toFixed(2) + "GB" +} + + +function Env(name,opts){class Http{constructor(env){this.env=env};send(opts,method='GET'){opts=typeof opts==='string'?{url:opts}:opts;let sender=this.get;if(method==='POST'){sender=this.post};return new Promise((resolve,reject)=>{sender.call(this,opts,(err,resp,body)=>{if(err)reject(err);else resolve(resp)})})};get(opts){return this.send.call(this.env,opts)};post(opts){return this.send.call(this.env,opts,'POST')}};return new(class{constructor(name,opts){this.name=name,this.http=new Http(this),this.data=null,this.dataFile='box.dat',this.logs=[],this.isMute=false,this.isNeedRewrite=false,this.logSeparator='\n';this.startTime=new Date().getTime();Object.assign(this,opts);this.log('',`🔔${this.name}, 开始!`)};isNode(){return'undefined'!==typeof module&&!!module.exports};isQuanX(){return'undefined'!==typeof $task};isSurge(){return'undefined'!==typeof $httpClient&&'undefined'===typeof $loon};isLoon(){return'undefined'!==typeof $loon};toObj(str,defaultValue=null){try{return JSON.parse(str)}catch{return defaultValue}};toStr(obj,defaultValue=null){try{return JSON.stringify(obj)}catch{return defaultValue}};getjson(key,defaultValue){let json=defaultValue;const val=this.getdata(key);if(val){try{json=JSON.parse(this.getdata(key))}catch{}};return json};setjson(val,key){try{return this.setdata(JSON.stringify(val),key)}catch{return false}}; getScript(url){return new Promise((resolve)=>{this.get({url},(err,resp,body)=>resolve(body))})};runScript(script,runOpts){return new Promise((resolve)=>{let httpapi=this.getdata('@chavy_boxjs_userCfgs.httpapi');httpapi=httpapi?httpapi.replace(/\n/g,'').trim():httpapi;let httpapi_timeout=this.getdata('@chavy_boxjs_userCfgs.httpapi_timeout');httpapi_timeout=httpapi_timeout?httpapi_timeout*1:20;httpapi_timeout=runOpts&&runOpts.timeout?runOpts.timeout:httpapi_timeout;const[key,addr]=httpapi.split('@');const opts={url:`http://${addr}/v1/scripting/evaluate`,body:{script_text:script,mock_type:'cron',timeout:httpapi_timeout},headers:{'X-Key':key,'Accept':'*/*'}};this.post(opts,(err,resp,body)=>resolve(body))}).catch((e)=>this.logErr(e))};loaddata(){if(this.isNode()){this.fs=this.fs?this.fs:require('fs');this.path=this.path?this.path:require('path');const curDirDataFilePath=this.path.resolve(this.dataFile);const rootDirDataFilePath=this.path.resolve(process.cwd(),this.dataFile);const isCurDirDataFile=this.fs.existsSync(curDirDataFilePath);const isRootDirDataFile=!isCurDirDataFile&&this.fs.existsSync(rootDirDataFilePath);if(isCurDirDataFile||isRootDirDataFile){const datPath=isCurDirDataFile?curDirDataFilePath:rootDirDataFilePath;try{return JSON.parse(this.fs.readFileSync(datPath))}catch(e){return{}}}else return{}}else return{}};writedata(){if(this.isNode()){this.fs=this.fs?this.fs:require('fs');this.path=this.path?this.path:require('path');const curDirDataFilePath=this.path.resolve(this.dataFile);const rootDirDataFilePath=this.path.resolve(process.cwd(),this.dataFile);const isCurDirDataFile=this.fs.existsSync(curDirDataFilePath);const isRootDirDataFile=!isCurDirDataFile&&this.fs.existsSync(rootDirDataFilePath);const jsondata=JSON.stringify(this.data);if(isCurDirDataFile){this.fs.writeFileSync(curDirDataFilePath,jsondata)}else if(isRootDirDataFile){this.fs.writeFileSync(rootDirDataFilePath,jsondata)}else{this.fs.writeFileSync(curDirDataFilePath,jsondata)}}};lodash_get(source,path,defaultValue=undefined){const paths=path.replace(/\[(\d+)\]/g,'.$1').split('.');let result=source;for(const p of paths){result=Object(result)[p];if(result===undefined){return defaultValue}};return result};lodash_set(obj,path,value){if(Object(obj)!==obj)return obj;if(!Array.isArray(path))path=path.toString().match(/[^.[\]]+/g)||[];path.slice(0,-1).reduce((a,c,i)=>(Object(a[c])===a[c]?a[c]:(a[c]=Math.abs(path[i+1])>>0===+path[i+1]?[]:{})),obj)[path[path.length-1]]=value;return obj};getdata(key){let val=this.getval(key);if(/^@/.test(key)){const[,objkey,paths]=/^@(.*?)\.(.*?)$/.exec(key);const objval=objkey?this.getval(objkey):'';if(objval){try{const objedval=JSON.parse(objval);val=objedval?this.lodash_get(objedval,paths,''):val}catch(e){val=''}}};return val};setdata(val,key){let issuc=false;if(/^@/.test(key)){const[,objkey,paths]=/^@(.*?)\.(.*?)$/.exec(key);const objdat=this.getval(objkey);const objval=objkey?(objdat==='null'?null:objdat||'{}'):'{}';try{const objedval=JSON.parse(objval);this.lodash_set(objedval,paths,val);issuc=this.setval(JSON.stringify(objedval),objkey)}catch(e){const objedval={};this.lodash_set(objedval,paths,val);issuc=this.setval(JSON.stringify(objedval),objkey)}}else{issuc=this.setval(val,key)};return issuc};getval(key){if(this.isSurge()||this.isLoon()){return $persistentStore.read(key)}else if(this.isQuanX()){return $prefs.valueForKey(key)}else if(this.isNode()){this.data=this.loaddata();return this.data[key]}else{return(this.data&&this.data[key])||null}};setval(val,key){if(this.isSurge()||this.isLoon()){return $persistentStore.write(val,key)}else if(this.isQuanX()){return $prefs.setValueForKey(val,key)}else if(this.isNode()){this.data=this.loaddata(),this.data[key]=val,this.writedata();return true}else{return(this.data&&this.data[key])||null}};initGotEnv(opts){this.got=this.got?this.got:require('got');this.cktough=this.cktough?this.cktough:require('tough-cookie');this.ckjar=this.ckjar?this.ckjar:new this.cktough.CookieJar();if(opts){opts.headers=opts.headers?opts.headers:{};if(undefined===opts.headers.Cookie&&undefined===opts.cookieJar){opts.cookieJar=this.ckjar}}}; get(opts,callback=()=>{}){if(opts.headers){delete opts.headers['Content-Type'];delete opts.headers['Content-Length']};if(this.isSurge()||this.isLoon()){if(this.isSurge()&&this.isNeedRewrite){opts.headers=opts.headers||{};Object.assign(opts.headers,{'X-Surge-Skip-Scripting':false})};$httpClient.get(opts,(err,resp,body)=>{if(!err&&resp){resp.body=body,resp.statusCode=resp.status};callback(err,resp,body)})}else if(this.isQuanX()){if(this.isNeedRewrite){opts.opts=opts.opts||{};Object.assign(opts.opts,{hints:false})};$task.fetch(opts).then((resp)=>{const{statusCode:status,statusCode,headers,body}=resp;callback(null,{status,statusCode,headers,body},body)},(err)=>callback(err))}else if(this.isNode()){this.initGotEnv(opts);this.got(opts).on('redirect',(resp,nextOpts)=>{try{if(resp.headers['set-cookie']){const ck=resp.headers['set-cookie'].map(this.cktough.Cookie.parse).toString();if(ck){this.ckjar.setCookieSync(ck,null)};nextOpts.cookieJar=this.ckjar}}catch(e){this.logErr(e)}}).then((resp)=>{const{statusCode:status,statusCode,headers,body}=resp;callback(null,{status,statusCode,headers,body},body)},(err)=>{const{message:error,response:resp}=err;callback(error,resp,resp&&resp.body)})}};post(opts,callback=()=>{}){if(opts.body&&opts.headers&&!opts.headers['Content-Type']){opts.headers['Content-Type']='application/x-www-form-urlencoded'};if(opts.headers)delete opts.headers['Content-Length'];if(this.isSurge()||this.isLoon()){if(this.isSurge()&&this.isNeedRewrite){opts.headers=opts.headers||{};Object.assign(opts.headers,{'X-Surge-Skip-Scripting':false})};$httpClient.post(opts,(err,resp,body)=>{if(!err&&resp){resp.body=body,resp.statusCode=resp.status};callback(err,resp,body)})}else if(this.isQuanX()){opts.method='POST';if(this.isNeedRewrite){opts.opts=opts.opts||{};Object.assign(opts.opts,{hints:false})};$task.fetch(opts).then((resp)=>{const{statusCode:status,statusCode,headers,body}=resp;callback(null,{status,statusCode,headers,body},body)},(err)=>callback(err))}else if(this.isNode()){this.initGotEnv(opts);const{url,..._opts}=opts;this.got.post(url,_opts).then((resp)=>{const{statusCode:status,statusCode,headers,body}=resp;callback(null,{status,statusCode,headers,body},body)},(err)=>{const{message:error,response:resp}=err;callback(error,resp,resp&&resp.body)})}};time(fmt,ts=null){const date=ts?new Date(ts):new Date();var o={"M+":date.getMonth()+1,"d+":date.getDate(),"h":date.getHours()%12==0?12:date.getHours()/12<1?"上午"+date.getHours()%12:"下午"+date.getHours()%12,"H+":date.getHours(),"m+":date.getMinutes(),"s+":date.getSeconds(),"q+":Math.floor((date.getMonth()+3)/3),"S":date.getMilliseconds()};var week={"0":"\u65e5","1":"\u4e00","2":"\u4e8c","3":"\u4e09","4":"\u56db","5":"\u4e94","6":"\u516d"};if(/(y+)/.test(fmt)){fmt=fmt.replace(RegExp.$1,(date.getFullYear()+"").substr(4-RegExp.$1.length))};if(/(E+)/.test(fmt)){fmt=fmt.replace(RegExp.$1,((RegExp.$1.length>1)?(RegExp.$1.length>2?"\u661f\u671f":"\u5468"):"")+week[date.getDay()+""])};for(var k in o){if(new RegExp("("+k+")").test(fmt)){fmt=fmt.replace(RegExp.$1,(RegExp.$1.length==1)?(o[k]):(("00"+o[k]).substr((""+o[k]).length)))}};return fmt};msg(title=name,subt='',desc='',opts){const toEnvOpts=(rawopts)=>{if(!rawopts)return rawopts;if(typeof rawopts==='string'){if(this.isLoon())return rawopts;else if(this.isQuanX())return{'open-url':rawopts};else if(this.isSurge())return{url:rawopts};else return undefined}else if(typeof rawopts==='object'){if(this.isLoon()){let openUrl=rawopts.openUrl||rawopts.url||rawopts['open-url'];let mediaUrl=rawopts.mediaUrl||rawopts['media-url'];return{openUrl,mediaUrl}}else if(this.isQuanX()){let openUrl=rawopts['open-url']||rawopts.url||rawopts.openUrl;let mediaUrl=rawopts['media-url']||rawopts.mediaUrl;return{'open-url':openUrl,'media-url':mediaUrl}}else if(this.isSurge()){let openUrl=rawopts.url||rawopts.openUrl||rawopts['open-url'];return{url:openUrl}}}else{return undefined}};if(!this.isMute){if(this.isSurge()||this.isLoon()){$notification.post(title,subt,desc,toEnvOpts(opts))}else if(this.isQuanX()){$notify(title,subt,desc,toEnvOpts(opts))}};if(!this.isMuteLog){let logs=['','==============📣\u7CFB\u7EDF\u901A\u77E5📣=============='];logs.push(title);subt?logs.push(subt):'';desc?logs.push(desc):'';console.log(logs.join('\n'));this.logs=this.logs.concat(logs)}};log(...logs){if(logs.length>0){this.logs=[...this.logs,...logs]};console.log(logs.join(this.logSeparator))};logErr(err,msg){const isPrintSack=!this.isSurge()&&!this.isQuanX()&&!this.isLoon();if(!isPrintSack){this.log('',`❗️${this.name}, \u9519\u8BEF!`,err)}else{this.log('',`❗️${this.name}, \u9519\u8BEF!`,err.stack)}};wait(time){return new Promise((resolve)=>setTimeout(resolve,time))};done(val={}){const endTime=new Date().getTime();const costTime=(endTime-this.startTime)/1000;this.log('',`🔔${this.name}, \u7ED3\u675F! 🕛 ${costTime} \u79D2`);this.log();if(this.isSurge()||this.isQuanX()||this.isLoon()){$done(val)}}})(name,opts)} diff --git a/Task/dianshijia.js b/Task/dianshijia.js index 3ebf16ea2a..d067693f14 100644 --- a/Task/dianshijia.js +++ b/Task/dianshijia.js @@ -1,52 +1,18 @@ /* -更新时间: 2020-10-13 21:21 +更新时间: 2020-11-16 09:40 赞赏:电视家邀请码`893988`,农妇山泉 -> 有点咸,万分感谢 本脚本仅适用于电视家签到,支持Actions多账号运行,请用'#'或者换行隔开‼️ -获取Cookie方法: -1.将下方[rewrite_local]和[Task]地址复制的相应的区域,无需添加 hostname,每日7点、12点、20点各运行一次,其他随意 -2.APP登陆账号后,点击菜单栏'领现金',即可获取Cookie,进入提现页面,点击随机金额,可获取提现地址!! -3.非专业人士制作,欢迎各位大佬提出宝贵意见和指导 -By Facsuny -感谢 chavyleung 等 -~~~~~~~~~~~~~~~~~~~~ -loon 2.10+ : -[Script] -cron "04 00 * * *" script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/dianshijia.js, tag=电视家 - -http-request http:\/\/api\.gaoqingdianshi\.com\/api\/v\d\/sign\/signin script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/dianshijia.js, timeout=10, tag=电视家 - -http-request http:\/\/api\.gaoqingdianshi\.com\/api\/v2\/cash\/withdrawal script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/dianshijia.js, timeout=10, tag=电视家 -~~~~~~~~~~~~~~~~~~~~~ -# 获取电视家 Cookie. -Surge 4.0 -[Script] -电视家 = type=cron,cronexp=0 8 0 * * *,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/dianshijia.js,script-update-interval=0 - -电视家 = type=http-request,pattern=http:\/\/api\.gaoqingdianshi\.com\/api\/v\d\/sign\/signin,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/dianshijia.js - -电视家 = type=http-request,pattern=http:\/\/api\.gaoqingdianshi\.com\/api\/v2\/cash\/withdrawal,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/dianshijia.js -~~~~~~~~~~~~~~~~~~ - -QX 1.0.6+ : -[task_local] -0 9 * * * https://raw.githubusercontent.com/Sunert/Scripts/master/Task/dianshijia.js - -[rewrite_local] -http:\/\/api\.gaoqingdianshi\.com\/api\/v\d\/sign\/signin url script-request-header https://raw.githubusercontent.com/Sunert/Scripts/master/Task/dianshijia.js - -http:\/\/api\.gaoqingdianshi\.com\/api\/v2\/cash\/withdrawal url script-request-header https://raw.githubusercontent.com/Sunert/Scripts/master/Task/dianshijia.js -~~~~~~~~~~~~~~~~~ - */ const walkstep = '20000';//每日步数设置,可设置0-20000 const gametimes = "1999"; //游戏时长 const logs = 0 //响应日志开关,默认关闭 const $ = new Env('电视家') const notify = $.isNode() ? require('./sendNotify') : ''; - let sleeping = ""; +let sleeping = "",detail=``,subTitle=``; +let RewardId = $.getdata('REWARD')||'55'; //额外签到奖励,默认55为兑换0.2元额度,44为兑换1天VIP,42为兑换1888金币 const dianshijia_API = 'http://api.gaoqingdianshi.com/api' -let tokenArr = [], DsjurlArr = [], DrawalArr = [],drawalVal; +let tokenArr = [], DsjurlArr = [], DrawalArr = [],drawalCode=""; if ($.isNode()) { if (process.env.DSJ_HEADERS && process.env.DSJ_HEADERS.indexOf('#') > -1) { Dsjheaders = process.env.DSJ_HEADERS.split('#'); @@ -77,8 +43,6 @@ if ($.isNode()) { DrawalArr.push(Drawals[item]) } }); - console.log(`============ 脚本执行-国际标准时间(UTC):${new Date().toLocaleString()} =============\n`) - console.log(`============ 脚本执行-北京时间(UTC+8):${new Date(new Date().getTime() + 8 * 60 * 60 * 1000).toLocaleString()} =============\n`) } else { tokenArr.push($.getdata('sy_signheader_dsj')) DrawalArr.push($.getdata('drawal_dsj')) @@ -94,20 +58,31 @@ if (isGetCookie = typeof $request !== 'undefined') { $.msg($.name, '【提示】请先获取电视家一cookie') return; } - console.log(`------------- 共${tokenArr.length}个账号\n`) + timeZone = new Date().getTimezoneOffset() / 60; + timestamp = Date.now()+ (8+timeZone) * 60 * 60 * 1000; + bjTime = new Date(timestamp).toLocaleString('zh',{hour12:false,timeZoneName: 'long'}); + console.log(`\n === 脚本执行 ${bjTime} ===\n`); + console.log(`------------- 共${tokenArr.length}个账号`); + if(new Date().getTimezoneOffset()/60 != '-8'&&$.time('HH')<'16'){ + time = new Date(new Date(new Date().toLocaleDateString()).getTime())/1000-28800 + console.log(time) + } else if(new Date().getTimezoneOffset()/60 != '-8'&&$.time('HH')>'16'){ + time = new Date(new Date(new Date().toLocaleDateString()).getTime())/1000+16*60*60 + } else { + time = new Date(new Date(new Date().toLocaleDateString()).getTime())/1000 + } for (let i = 0; i < tokenArr.length; i++) { if (tokenArr[i]) { signheaderVal = tokenArr[i]; drawalVal = DrawalArr[i]; $.index = i + 1; - console.log(`开始【电视家${$.index}】`) + console.log(`\n\n开始【电视家${$.index}】`) await signin(); // 签到 await signinfo(); // 签到信息 + await Addsign(); // 额外奖励,默认额度 if (drawalVal != undefined){ - await Withdrawal() - } else { - detail += `【金额提现】❌ 请获取提现地址 \n` - };// 金额提现 + await Withdrawal() + } else { detail += `【金额提现】❌ 请获取提现地址 \n`}; await run(); await tasks(); // 任务状态 await getGametime();// 游戏时长 @@ -115,7 +90,7 @@ if (isGetCookie = typeof $request !== 'undefined') { await cash(); // 现金 await cashlist(); // 现金列表 await coinlist(); // 金币列表 - if ($.isNode()&& process.env.DSJ_NOTIFY_CONTROL == false) { + if ($.isNode() && process.env.DSJ_NOTIFY_CONTROL&& drawalCode == '0') { await notify.sendNotify($.name, subTitle+'\n'+ detail) } } @@ -139,7 +114,7 @@ function GetCookie() { } } async function run() { - if ($.isNode()) { + if ($.isNode()&&new Date().getTimezoneOffset() == '0') { if ($.time('HH')>11){ await sleep(); await CarveUp(); @@ -206,7 +181,7 @@ function signinfo() { $.get({ url: `${dianshijia_API}/v4/sign/get`, headers: JSON.parse(signheaderVal)}, (error, response, data) => { if(logs)$.log(`${$.name}, 签到信息: ${data}\n`) - const result = JSON.parse(data) + let result = JSON.parse(data) if (result.errCode == 0) { var d = `${result.data.currentDay}` @@ -216,8 +191,8 @@ function signinfo() { {detail += ` 连续签到${d}天\n` } } - resolve() } + resolve() }) }) } @@ -226,7 +201,7 @@ function total() { return new Promise((resolve, reject) => { $.get({url: `${dianshijia_API}/coin/info`, headers: JSON.parse(signheaderVal)}, (error, response, data) => { if(logs)$.log(`${$.name}, 总计: ${data}\n`) - const result = JSON.parse(data) + let result = JSON.parse(data) subTitle = `待兑换金币: ${result.data.coin} ` try{ if(result.data.tempCoin){ @@ -235,10 +210,11 @@ function total() { $.get({ url: `http://api.gaoqingdianshi.com/api/coin/temp/exchange?id=`+coinid, headers: JSON.parse(signheaderVal)}, (error, response, data)) } } - } - catch(err){ - console.log(err) } - resolve() + resolve() + } catch(e){ + console.log(e) + resolve() + } }) }) } @@ -247,9 +223,11 @@ function cash() { $.get({ url: `${dianshijia_API}/cash/info`, headers: JSON.parse(signheaderVal)}, (error, response, data) => { if(logs)$.log(`现金: ${data}\n`) - const cashresult = JSON.parse(data) - subTitle += '现金:'+ cashresult.data.amount/100+'元 额度:'+cashresult.data.withdrawalQuota/100+'元' - cashtotal = cashresult.data.totalWithdrawn/100 + let cashresult = JSON.parse(data) + if(cashresult.errCode=="0"){ + subTitle += '现金:'+ cashresult.data.amount/100+'元 额度:'+cashresult.data.withdrawalQuota/100+'元' + cashtotal = cashresult.data.totalWithdrawn/100 + } resolve() }) }) @@ -258,29 +236,26 @@ function cashlist() { return new Promise((resolve, reject) => { $.get({ url: `${dianshijia_API}/cash/detail`, headers: JSON.parse(signheaderVal)}, (error, response, data) => { - const result = JSON.parse(data) - let totalcash = Number(),cashres = "" - var time = new Date(new Date(new Date().toLocaleDateString()).getTime())/1000 - try{ - if (result.errCode == 0) { - for (i=0;i=time){ - cashres = `✅ 今日提现:`+result.data[i].amount/100+`元 ` +(result.data[i].type == '2' && result.data[i].ctime >= time ){ + cashres = `✅ 今日提现:`+result.data[i].amount/100+`元 ` } } - if(cashres&&cashtotal){ + if(cashres && cashtotal){ detail += `【提现结果】`+cashres+`共计提现:`+cashtotal+`元\n` } - else if(cashtotal){ + else if(!cashres&&cashtotal){ detail += `【提现结果】今日未提现 共计提现:`+cashtotal+`元\n` } - } - } - catch (error){ + } else { console.log(`提现列表失败,可忽略: ${data}`) - } - resolve() + } + resolve() }) }) } @@ -296,18 +271,21 @@ function tasks(tkcode) { function dotask(code) { return new Promise((resolve, reject) => { $.get({ url: `${dianshijia_API}/v4/task/complete?code=${code}`, headers: JSON.parse(signheaderVal)}, (error, response, data) => { - taskres = JSON.parse(data) - if (taskres.errCode==0){ - console.log('任务代码:'+code+',获得金币:'+taskres.data.getCoin) - if (code== 'playTask'&&taskres.data.doneStatus == 3) { - detail += `【播放任务】🔕 完成/共计 `+taskres.data.dayCompCount+`/`+taskres.data.dayDoCountMax+` 次\n` + let taskres = JSON.parse(data), + taskcode = taskres.errCode; + if (taskcode == 0){ + CompCount = taskres.data.dayCompCount + CountMax = taskres.data.dayDoCountMax + console.log('任务代码:'+code+',获得金币:'+taskres.data.getCoin) + if ( code == 'playTask'&&taskres.data.doneStatus == 3) { + detail += `【播放任务】🔕 完成/共计 `+CompCount+`/`+CountMax+` 次\n` } } - if (taskres.errCode==4000){ + else if (taskcode == '4000'){ //console.log('任务代码:'+code+','+taskres.msg) } + resolve() }) - resolve() }) } @@ -317,13 +295,13 @@ function walk() { $.get(url, (error, response, data) => { if(logs)$.log(`走路任务: ${data}\n`) - const result = JSON.parse(data) + let result = JSON.parse(data) if (result.data.unGetCoin>10){ $.get({ url: `${dianshijia_API}/taskext/getCoin?code=walk&coin=${result.data.unGetCoin}&ext=1`, headers: JSON.parse(signheaderVal)}, (error, response, data) => { }) } - resolve() + resolve() }) }) } @@ -334,16 +312,17 @@ function sleep() { $.get(url, (error, response, data) => { try { if(logs)$.log(`睡觉任务: ${data}\n`) - const result = JSON.parse(data) - if (result.errCode==0){ - sleeping = result.data.name+'报名成功 🛌' + let sleepres = JSON.parse(data) + if (sleepres.errCode==0){ + sleeping = sleepres.data.name+'报名成功 🛌' } -else if (result.errCode==4006){ +else if (sleepres.errCode==4006){ sleeping = '睡觉中😴' } else { sleeping = '' - } + } + resolve() } catch (e) { $.msg($.name, `睡觉结果: 失败`, `说明: ${e}`)} @@ -359,22 +338,20 @@ function wakeup() { $.get(url, (error, response, data) => { if(logs)$.log(`睡觉打卡: ${data}\n`) }) -resolve() + resolve() }) } - function coinlist() { return new Promise((resolve, reject) => { setTimeout(() => { let url = { url: `${dianshijia_API}/coin/detail`, headers: JSON.parse(signheaderVal)} $.get(url, (error, response, data) => { - //console.log(`金币列表: ${data}`) + //console.log(`金币列表: ${data}`) let result = JSON.parse(data) let onlamount = 0, vdamount = 0, gamestime = 0, todaysign = 0; - var time = new Date(new Date(new Date().toLocaleDateString()).getTime())/1000 try { for (i=0;i= time;i++){ if (result.data[i].from=="领取走路金币"){ @@ -424,12 +401,11 @@ function coinlist() { detail += `【任务统计】共完成${i+1}次任务🌷` } $.msg($.name+` `+sleeping, subTitle, detail) - resolve() - } catch(error) { - console.log(`获取任务金币列表失败,错误代码${error}+ \n响应数据:${data}`) - $.msg($.name+` `+sleeping, subTitle, detail) - resolve() + } catch(e) { + console.log(`获取任务金币列表失败,错误代码${e}+ \n响应数据:${data}`) + $.msg($.name+` 获取金币详情失败 `, subTitle, detail) } + resolve() }) },1000) }) @@ -447,8 +423,8 @@ function CarveUp() { if (result.errCode == 0) { detail += `【金币瓜分】✅ 报名成功\n` } + resolve() }) -resolve() }) } function getCUpcoin() { @@ -462,11 +438,12 @@ function getCUpcoin() { function Withdrawal() { return new Promise((resolve, reject) => { $.get({url: drawalVal, headers: JSON.parse(signheaderVal)}, (error, response, data) => { - if(logs)$.log(`金币随机兑换 : ${data}\n`) - const result = JSON.parse(data) - if (result.errCode == 0) { - detail += `【金额提现】✅ 到账`+result.data.price/100+`元 🌷\n` - } + if(logs)$.log(`金币随机兑换 : ${data}\n`) + let todrawal = JSON.parse(data); + if (todrawal.errCode == 0) { + detail += `【金额提现】✅ 到账`+todrawal.data.price/100+`元 🌷\n` + drawalCode = todrawal.errCode + } resolve() }) }) @@ -480,7 +457,20 @@ function getGametime() { $.get(url, (error, response, data) => { if(logs)$.log(`游戏时长: ${data}\n`) }) -resolve() + resolve() + }) +} +function Addsign() { + return new Promise((resolve, reject) => { + let url = { + url: `${dianshijia_API}/sign/chooseAdditionalReward?rewardId=${RewardId}`, + headers: JSON.parse(signheaderVal), + } + $.get(url, (error, response, data) => { + if(logs)$.log(`额外签到: ${data}\n`) + }) + resolve() }) } -function Env(t,e){class s{constructor(t){this.env=t}send(t,e="GET"){t="string"==typeof t?{url:t}:t;let s=this.get;return"POST"===e&&(s=this.post),new Promise((e,i)=>{s.call(this,t,(t,s,r)=>{t?i(t):e(s)})})}get(t){return this.send.call(this.env,t)}post(t){return this.send.call(this.env,t,"POST")}}return new class{constructor(t,e){this.name=t,this.http=new s(this),this.data=null,this.dataFile="box.dat",this.logs=[],this.isMute=!1,this.isNeedRewrite=!1,this.logSeparator="\n",this.startTime=(new Date).getTime(),Object.assign(this,e),this.log("",`\ud83d\udd14${this.name}, \u5f00\u59cb!`)}isNode(){return"undefined"!=typeof module&&!!module.exports}isQuanX(){return"undefined"!=typeof $task}isSurge(){return"undefined"!=typeof $httpClient&&"undefined"==typeof $loon}isLoon(){return"undefined"!=typeof $loon}toObj(t,e=null){try{return JSON.parse(t)}catch{return e}}toStr(t,e=null){try{return JSON.stringify(t)}catch{return e}}getjson(t,e){let s=e;const i=this.getdata(t);if(i)try{s=JSON.parse(this.getdata(t))}catch{}return s}setjson(t,e){try{return this.setdata(JSON.stringify(t),e)}catch{return!1}}getScript(t){return new Promise(e=>{this.get({url:t},(t,s,i)=>e(i))})}runScript(t,e){return new Promise(s=>{let i=this.getdata("@chavy_boxjs_userCfgs.httpapi");i=i?i.replace(/\n/g,"").trim():i;let r=this.getdata("@chavy_boxjs_userCfgs.httpapi_timeout");r=r?1*r:20,r=e&&e.timeout?e.timeout:r;const[o,h]=i.split("@"),a={url:`http://${h}/v1/scripting/evaluate`,body:{script_text:t,mock_type:"cron",timeout:r},headers:{"X-Key":o,Accept:"*/*"}};this.post(a,(t,e,i)=>s(i))}).catch(t=>this.logErr(t))}loaddata(){if(!this.isNode())return{};{this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(this.dataFile),e=this.path.resolve(process.cwd(),this.dataFile),s=this.fs.existsSync(t),i=!s&&this.fs.existsSync(e);if(!s&&!i)return{};{const i=s?t:e;try{return JSON.parse(this.fs.readFileSync(i))}catch(t){return{}}}}}writedata(){if(this.isNode()){this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(this.dataFile),e=this.path.resolve(process.cwd(),this.dataFile),s=this.fs.existsSync(t),i=!s&&this.fs.existsSync(e),r=JSON.stringify(this.data);s?this.fs.writeFileSync(t,r):i?this.fs.writeFileSync(e,r):this.fs.writeFileSync(t,r)}}lodash_get(t,e,s){const i=e.replace(/\[(\d+)\]/g,".$1").split(".");let r=t;for(const t of i)if(r=Object(r)[t],void 0===r)return s;return r}lodash_set(t,e,s){return Object(t)!==t?t:(Array.isArray(e)||(e=e.toString().match(/[^.[\]]+/g)||[]),e.slice(0,-1).reduce((t,s,i)=>Object(t[s])===t[s]?t[s]:t[s]=Math.abs(e[i+1])>>0==+e[i+1]?[]:{},t)[e[e.length-1]]=s,t)}getdata(t){let e=this.getval(t);if(/^@/.test(t)){const[,s,i]=/^@(.*?)\.(.*?)$/.exec(t),r=s?this.getval(s):"";if(r)try{const t=JSON.parse(r);e=t?this.lodash_get(t,i,""):e}catch(t){e=""}}return e}setdata(t,e){let s=!1;if(/^@/.test(e)){const[,i,r]=/^@(.*?)\.(.*?)$/.exec(e),o=this.getval(i),h=i?"null"===o?null:o||"{}":"{}";try{const e=JSON.parse(h);this.lodash_set(e,r,t),s=this.setval(JSON.stringify(e),i)}catch(e){const o={};this.lodash_set(o,r,t),s=this.setval(JSON.stringify(o),i)}}else s=this.setval(t,e);return s}getval(t){return this.isSurge()||this.isLoon()?$persistentStore.read(t):this.isQuanX()?$prefs.valueForKey(t):this.isNode()?(this.data=this.loaddata(),this.data[t]):this.data&&this.data[t]||null}setval(t,e){return this.isSurge()||this.isLoon()?$persistentStore.write(t,e):this.isQuanX()?$prefs.setValueForKey(t,e):this.isNode()?(this.data=this.loaddata(),this.data[e]=t,this.writedata(),!0):this.data&&this.data[e]||null}initGotEnv(t){this.got=this.got?this.got:require("got"),this.cktough=this.cktough?this.cktough:require("tough-cookie"),this.ckjar=this.ckjar?this.ckjar:new this.cktough.CookieJar,t&&(t.headers=t.headers?t.headers:{},void 0===t.headers.Cookie&&void 0===t.cookieJar&&(t.cookieJar=this.ckjar))}get(t,e=(()=>{})){t.headers&&(delete t.headers["Content-Type"],delete t.headers["Content-Length"]),this.isSurge()||this.isLoon()?(this.isSurge()&&this.isNeedRewrite&&(t.headers=t.headers||{},Object.assign(t.headers,{"X-Surge-Skip-Scripting":!1})),$httpClient.get(t,(t,s,i)=>{!t&&s&&(s.body=i,s.statusCode=s.status),e(t,s,i)})):this.isQuanX()?(this.isNeedRewrite&&(t.opts=t.opts||{},Object.assign(t.opts,{hints:!1})),$task.fetch(t).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>e(t))):this.isNode()&&(this.initGotEnv(t),this.got(t).on("redirect",(t,e)=>{try{if(t.headers["set-cookie"]){const s=t.headers["set-cookie"].map(this.cktough.Cookie.parse).toString();this.ckjar.setCookieSync(s,null),e.cookieJar=this.ckjar}}catch(t){this.logErr(t)}}).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>{const{message:s,response:i}=t;e(s,i,i&&i.body)}))}post(t,e=(()=>{})){if(t.body&&t.headers&&!t.headers["Content-Type"]&&(t.headers["Content-Type"]="application/x-www-form-urlencoded"),t.headers&&delete t.headers["Content-Length"],this.isSurge()||this.isLoon())this.isSurge()&&this.isNeedRewrite&&(t.headers=t.headers||{},Object.assign(t.headers,{"X-Surge-Skip-Scripting":!1})),$httpClient.post(t,(t,s,i)=>{!t&&s&&(s.body=i,s.statusCode=s.status),e(t,s,i)});else if(this.isQuanX())t.method="POST",this.isNeedRewrite&&(t.opts=t.opts||{},Object.assign(t.opts,{hints:!1})),$task.fetch(t).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>e(t));else if(this.isNode()){this.initGotEnv(t);const{url:s,...i}=t;this.got.post(s,i).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>{const{message:s,response:i}=t;e(s,i,i&&i.body)})}}time(t){let e={"M+":(new Date).getMonth()+1,"d+":(new Date).getDate(),"H+":(new Date).getHours(),"m+":(new Date).getMinutes(),"s+":(new Date).getSeconds(),"q+":Math.floor(((new Date).getMonth()+3)/3),S:(new Date).getMilliseconds()};/(y+)/.test(t)&&(t=t.replace(RegExp.$1,((new Date).getFullYear()+"").substr(4-RegExp.$1.length)));for(let s in e)new RegExp("("+s+")").test(t)&&(t=t.replace(RegExp.$1,1==RegExp.$1.length?e[s]:("00"+e[s]).substr((""+e[s]).length)));return t}msg(e=t,s="",i="",r){const o=t=>{if(!t)return t;if("string"==typeof t)return this.isLoon()?t:this.isQuanX()?{"open-url":t}:this.isSurge()?{url:t}:void 0;if("object"==typeof t){if(this.isLoon()){let e=t.openUrl||t.url||t["open-url"],s=t.mediaUrl||t["media-url"];return{openUrl:e,mediaUrl:s}}if(this.isQuanX()){let e=t["open-url"]||t.url||t.openUrl,s=t["media-url"]||t.mediaUrl;return{"open-url":e,"media-url":s}}if(this.isSurge()){let e=t.url||t.openUrl||t["open-url"];return{url:e}}}};this.isMute||(this.isSurge()||this.isLoon()?$notification.post(e,s,i,o(r)):this.isQuanX()&&$notify(e,s,i,o(r)));let h=["","==============\ud83d\udce3\u7cfb\u7edf\u901a\u77e5\ud83d\udce3=============="];h.push(e),s&&h.push(s),i&&h.push(i),console.log(h.join("\n")),this.logs=this.logs.concat(h)}log(...t){t.length>0&&(this.logs=[...this.logs,...t]),console.log(t.join(this.logSeparator))}logErr(t,e){const s=!this.isSurge()&&!this.isQuanX()&&!this.isLoon();s?this.log("",`\u2757\ufe0f${this.name}, \u9519\u8bef!`,t.stack):this.log("",`\u2757\ufe0f${this.name}, \u9519\u8bef!`,t)}wait(t){return new Promise(e=>setTimeout(e,t))}done(t={}){const e=(new Date).getTime(),s=(e-this.startTime)/1e3;this.log("",`\ud83d\udd14${this.name}, \u7ed3\u675f! \ud83d\udd5b ${s} \u79d2`),this.log(),(this.isSurge()||this.isQuanX()||this.isLoon())&&$done(t)}}(t,e)} + +function Env(t,e){class s{constructor(t){this.env=t}send(t,e="GET"){t="string"==typeof t?{url:t}:t;let s=this.get;return"POST"===e&&(s=this.post),new Promise((e,i)=>{s.call(this,t,(t,s,r)=>{t?i(t):e(s)})})}get(t){return this.send.call(this.env,t)}post(t){return this.send.call(this.env,t,"POST")}}return new class{constructor(t,e){this.name=t,this.http=new s(this),this.data=null,this.dataFile="box.dat",this.logs=[],this.isMute=!1,this.isNeedRewrite=!1,this.logSeparator="\n",this.startTime=(new Date).getTime(),Object.assign(this,e),this.log("",`\ud83d\udd14${this.name}, \u5f00\u59cb!`)}isNode(){return"undefined"!=typeof module&&!!module.exports}isQuanX(){return"undefined"!=typeof $task}isSurge(){return"undefined"!=typeof $httpClient&&"undefined"==typeof $loon}isLoon(){return"undefined"!=typeof $loon}toObj(t,e=null){try{return JSON.parse(t)}catch{return e}}toStr(t,e=null){try{return JSON.stringify(t)}catch{return e}}getjson(t,e){let s=e;const i=this.getdata(t);if(i)try{s=JSON.parse(this.getdata(t))}catch{}return s}setjson(t,e){try{return this.setdata(JSON.stringify(t),e)}catch{return!1}}getScript(t){return new Promise(e=>{this.get({url:t},(t,s,i)=>e(i))})}runScript(t,e){return new Promise(s=>{let i=this.getdata("@chavy_boxjs_userCfgs.httpapi");i=i?i.replace(/\n/g,"").trim():i;let r=this.getdata("@chavy_boxjs_userCfgs.httpapi_timeout");r=r?1*r:20,r=e&&e.timeout?e.timeout:r;const[o,h]=i.split("@"),a={url:`http://${h}/v1/scripting/evaluate`,body:{script_text:t,mock_type:"cron",timeout:r},headers:{"X-Key":o,Accept:"*/*"}};this.post(a,(t,e,i)=>s(i))}).catch(t=>this.logErr(t))}loaddata(){if(!this.isNode())return{};{this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(this.dataFile),e=this.path.resolve(process.cwd(),this.dataFile),s=this.fs.existsSync(t),i=!s&&this.fs.existsSync(e);if(!s&&!i)return{};{const i=s?t:e;try{return JSON.parse(this.fs.readFileSync(i))}catch(t){return{}}}}}writedata(){if(this.isNode()){this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(this.dataFile),e=this.path.resolve(process.cwd(),this.dataFile),s=this.fs.existsSync(t),i=!s&&this.fs.existsSync(e),r=JSON.stringify(this.data);s?this.fs.writeFileSync(t,r):i?this.fs.writeFileSync(e,r):this.fs.writeFileSync(t,r)}}lodash_get(t,e,s){const i=e.replace(/\[(\d+)\]/g,".$1").split(".");let r=t;for(const t of i)if(r=Object(r)[t],void 0===r)return s;return r}lodash_set(t,e,s){return Object(t)!==t?t:(Array.isArray(e)||(e=e.toString().match(/[^.[\]]+/g)||[]),e.slice(0,-1).reduce((t,s,i)=>Object(t[s])===t[s]?t[s]:t[s]=Math.abs(e[i+1])>>0==+e[i+1]?[]:{},t)[e[e.length-1]]=s,t)}getdata(t){let e=this.getval(t);if(/^@/.test(t)){const[,s,i]=/^@(.*?)\.(.*?)$/.exec(t),r=s?this.getval(s):"";if(r)try{const t=JSON.parse(r);e=t?this.lodash_get(t,i,""):e}catch(t){e=""}}return e}setdata(t,e){let s=!1;if(/^@/.test(e)){const[,i,r]=/^@(.*?)\.(.*?)$/.exec(e),o=this.getval(i),h=i?"null"===o?null:o||"{}":"{}";try{const e=JSON.parse(h);this.lodash_set(e,r,t),s=this.setval(JSON.stringify(e),i)}catch(e){const o={};this.lodash_set(o,r,t),s=this.setval(JSON.stringify(o),i)}}else s=this.setval(t,e);return s}getval(t){return this.isSurge()||this.isLoon()?$persistentStore.read(t):this.isQuanX()?$prefs.valueForKey(t):this.isNode()?(this.data=this.loaddata(),this.data[t]):this.data&&this.data[t]||null}setval(t,e){return this.isSurge()||this.isLoon()?$persistentStore.write(t,e):this.isQuanX()?$prefs.setValueForKey(t,e):this.isNode()?(this.data=this.loaddata(),this.data[e]=t,this.writedata(),!0):this.data&&this.data[e]||null}initGotEnv(t){this.got=this.got?this.got:require("got"),this.cktough=this.cktough?this.cktough:require("tough-cookie"),this.ckjar=this.ckjar?this.ckjar:new this.cktough.CookieJar,t&&(t.headers=t.headers?t.headers:{},void 0===t.headers.Cookie&&void 0===t.cookieJar&&(t.cookieJar=this.ckjar))}get(t,e=(()=>{})){t.headers&&(delete t.headers["Content-Type"],delete t.headers["Content-Length"]),this.isSurge()||this.isLoon()?(this.isSurge()&&this.isNeedRewrite&&(t.headers=t.headers||{},Object.assign(t.headers,{"X-Surge-Skip-Scripting":!1})),$httpClient.get(t,(t,s,i)=>{!t&&s&&(s.body=i,s.statusCode=s.status),e(t,s,i)})):this.isQuanX()?(this.isNeedRewrite&&(t.opts=t.opts||{},Object.assign(t.opts,{hints:!1})),$task.fetch(t).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>e(t))):this.isNode()&&(this.initGotEnv(t),this.got(t).on("redirect",(t,e)=>{try{if(t.headers["set-cookie"]){const s=t.headers["set-cookie"].map(this.cktough.Cookie.parse).toString();s&&this.ckjar.setCookieSync(s,null),e.cookieJar=this.ckjar}}catch(t){this.logErr(t)}}).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>{const{message:s,response:i}=t;e(s,i,i&&i.body)}))}post(t,e=(()=>{})){if(t.body&&t.headers&&!t.headers["Content-Type"]&&(t.headers["Content-Type"]="application/x-www-form-urlencoded"),t.headers&&delete t.headers["Content-Length"],this.isSurge()||this.isLoon())this.isSurge()&&this.isNeedRewrite&&(t.headers=t.headers||{},Object.assign(t.headers,{"X-Surge-Skip-Scripting":!1})),$httpClient.post(t,(t,s,i)=>{!t&&s&&(s.body=i,s.statusCode=s.status),e(t,s,i)});else if(this.isQuanX())t.method="POST",this.isNeedRewrite&&(t.opts=t.opts||{},Object.assign(t.opts,{hints:!1})),$task.fetch(t).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>e(t));else if(this.isNode()){this.initGotEnv(t);const{url:s,...i}=t;this.got.post(s,i).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>{const{message:s,response:i}=t;e(s,i,i&&i.body)})}}time(t){let e={"M+":(new Date).getMonth()+1,"d+":(new Date).getDate(),"H+":(new Date).getHours(),"m+":(new Date).getMinutes(),"s+":(new Date).getSeconds(),"q+":Math.floor(((new Date).getMonth()+3)/3),S:(new Date).getMilliseconds()};/(y+)/.test(t)&&(t=t.replace(RegExp.$1,((new Date).getFullYear()+"").substr(4-RegExp.$1.length)));for(let s in e)new RegExp("("+s+")").test(t)&&(t=t.replace(RegExp.$1,1==RegExp.$1.length?e[s]:("00"+e[s]).substr((""+e[s]).length)));return t}msg(e=t,s="",i="",r){const o=t=>{if(!t)return t;if("string"==typeof t)return this.isLoon()?t:this.isQuanX()?{"open-url":t}:this.isSurge()?{url:t}:void 0;if("object"==typeof t){if(this.isLoon()){let e=t.openUrl||t.url||t["open-url"],s=t.mediaUrl||t["media-url"];return{openUrl:e,mediaUrl:s}}if(this.isQuanX()){let e=t["open-url"]||t.url||t.openUrl,s=t["media-url"]||t.mediaUrl;return{"open-url":e,"media-url":s}}if(this.isSurge()){let e=t.url||t.openUrl||t["open-url"];return{url:e}}}};if(this.isMute||(this.isSurge()||this.isLoon()?$notification.post(e,s,i,o(r)):this.isQuanX()&&$notify(e,s,i,o(r))),!this.isMuteLog){let t=["","==============\ud83d\udce3\u7cfb\u7edf\u901a\u77e5\ud83d\udce3=============="];t.push(e),s&&t.push(s),i&&t.push(i),console.log(t.join("\n")),this.logs=this.logs.concat(t)}}log(...t){t.length>0&&(this.logs=[...this.logs,...t]),console.log(t.join(this.logSeparator))}logErr(t,e){const s=!this.isSurge()&&!this.isQuanX()&&!this.isLoon();s?this.log("",`\u2757\ufe0f${this.name}, \u9519\u8bef!`,t.stack):this.log("",`\u2757\ufe0f${this.name}, \u9519\u8bef!`,t)}wait(t){return new Promise(e=>setTimeout(e,t))}done(t={}){const e=(new Date).getTime(),s=(e-this.startTime)/1e3;this.log("",`\ud83d\udd14${this.name}, \u7ed3\u675f! \ud83d\udd5b ${s} \u79d2`),this.log(),(this.isSurge()||this.isQuanX()||this.isLoon())&&$done(t)}}(t,e)} diff --git a/Task/formatJson.js b/Task/formatJson.js new file mode 100644 index 0000000000..5fd572045d --- /dev/null +++ b/Task/formatJson.js @@ -0,0 +1 @@ +function formatJson(json,options){var reg=null,formatted='',pad=0,PADDING=' ';options=options||{};options.newlineAfterColonIfBeforeBraceOrBracket=(options.newlineAfterColonIfBeforeBraceOrBracket===true)?true:false;options.spaceAfterColon=(options.spaceAfterColon===false)?false:true;if(typeof json!=='string'){json=JSON.stringify(json);}else{json=JSON.parse(json);json=JSON.stringify(json)};json=json.replace(/([\{\}])/g,'\r\n$1\r\n');json=json.replace(/([\[\]])/,'\r\n$1\r\n');json=json.replace(/(\,)/g,'$1\r\n');json=json.replace(/(\r\n\r\n)/g,'\r\n');json=json.replace(/\r\n\,/g,',');if(!options.newlineAfterColonIfBeforeBraceOrBracket){json=json.replace(/\:\r\n\{/g,':{');json=json.replace(/\:\r\n\[/g,':[')};if(options.spaceAfterColon){json=json.replace(/\:/g,':')};(json.split('\r\n')).forEach(function(node,index){var i=0,indent=0,padding='';if(node.match(/\{$/)||node.match(/\[$/)){indent=1}else if(node.match(/\}/)||node.match(/\]/)){if(pad!==0){pad-=1}}else{indent=0};for(i=0;i + var jsObj = '{$data}';//远程数据json,可替换为自己的json也可以使用下方json测试 + jsObj = jsObj.replace(/"/,""); + jsObj = jsObj.substring(0, jsObj.lastIndexOf('"')); + $("#show").html(formatJson(jsObj)); + //$("#show").html(jsObj); + Process(); + //格式化代码函数,已经用原生方式写好了不需要改动,直接引用就好 + function formatJson(json, options) { + var reg = null, + formatted = '', + pad = 0, + PADDING = ' '; + options = options || {}; + options.newlineAfterColonIfBeforeBraceOrBracket = (options.newlineAfterColonIfBeforeBraceOrBracket === true) ? true : false; + options.spaceAfterColon = (options.spaceAfterColon === false) ? false : true; + if (typeof json !== 'string') { + json = JSON.stringify(json); + } else { + json = JSON.parse(json); + json = JSON.stringify(json); + } + reg = /([\{\}])/g; + json = json.replace(reg, '\r\n$1\r\n'); + reg = /([\[\]])/g; + json = json.replace(reg, '\r\n$1\r\n'); + reg = /(\,)/g; + json = json.replace(reg, '$1\r\n'); + reg = /(\r\n\r\n)/g; + json = json.replace(reg, '\r\n'); + reg = /\r\n\,/g; + json = json.replace(reg, ','); + if (!options.newlineAfterColonIfBeforeBraceOrBracket) { + reg = /\:\r\n\{/g; + json = json.replace(reg, ':{'); + reg = /\:\r\n\[/g; + json = json.replace(reg, ':['); + } + if (options.spaceAfterColon) { + reg = /\:/g; + json = json.replace(reg, ':'); + } + (json.split('\r\n')).forEach(function (node, index) { + //console.log(node); + var i = 0, + indent = 0, + padding = ''; + + if (node.match(/\{$/) || node.match(/\[$/)) { + indent = 1; + } else if (node.match(/\}/) || node.match(/\]/)) { + if (pad !== 0) { + pad -= 1; + } + } else { + indent = 0; + } + + for (i = 0; i < pad; i++) { + padding += PADDING; + } + + formatted += padding + node + '\r\n'; + pad += indent; + }); + return formatted; + }; + //引用示例部分 + //(1)创建json格式或者从后台拿到对应的json格式 + //var originalJson = {"name": "binginsist", "sex": "男", "age": "25"}; + //下面用一个真实的json数据做测试 + //var originalJson = { + // "_errmsg":"ok", + // "result":[ + // ], + // "stat":"wechat", + // "_token":"", + // "weixinId":"900504", + // "_errcode":"0", + // "regionId":"00000000" + //} + // + //(2)调用formatJson函数,将json格式进行格式化 + //var resultJson = formatJson(originalJson); + (3)将格式化好后的json写入页面中 + //document.getElementById("writePlace").innerHTML = '
' +resultJson + '
';
+ 
+        //着色
+        function IsArray(obj) {
+          return obj &&
+              typeof obj === 'object' &&  typeof obj.length === 'number' && !(obj.propertyIsEnumerable('length'));
+        }
+        function Process() {
+            var json = $('#show').text();
+            console.log(json);
+            var html = "";
+            try {
+                if (json == "") {
+                    json = '""';
+                }
+                var obj = eval("[" + json + "]");
+                html = ProcessObject(obj[0], 0, false, false, false);
+                $("#show").html(html);
+            } catch(e) {
+            }
+        }
+        function ProcessObject(obj, indent, addComma, isArray, isPropertyContent) {
+            var html = "";
+            var comma = (addComma) ? ", ": "";
+            var type = typeof obj;
+            if (IsArray(obj)) {
+                if (obj.length == 0) {
+                    html += GetRow(indent, "[ ]" + comma, isPropertyContent);
+                } else {
+                    html += GetRow(indent, "[", isPropertyContent);
+                    for (var i = 0; i < obj.length; i++) {
+                        html += ProcessObject(obj[i], indent + 1, i < (obj.length - 1), true, false);
+                    }
+                    html += GetRow(indent, "]" + comma);
+                }
+            } else {
+                if (type == "object" && obj == null) {
+                    html += FormatLiteral("null", "", comma, indent, isArray, "Null");
+                } else {
+                    if (type == "object") {
+                        var numProps = 0;
+                        for (var prop in obj) {
+                            numProps++;
+                        }
+                        if (numProps == 0) {
+                            html += GetRow(indent, "{ }" + comma, isPropertyContent)
+                        } else {
+                            html += GetRow(indent, "{", isPropertyContent);
+                            var j = 0;
+                            for (var prop in obj) {
+                                html += GetRow(indent + 1, '"' + prop + '": ' + ProcessObject(obj[prop], indent + 1, ++j < numProps, false, true))
+                            }
+                            html += GetRow(indent, "}" + comma);
+                        }
+                    } else {
+                        if (type == "number") {
+                            html += FormatLiteral(obj, "", comma, indent, isArray, "Number");
+                        } else {
+                            if (type == "boolean") {
+                                html += FormatLiteral(obj, "", comma, indent, isArray, "Boolean");
+                            } else {
+                                if (type == "function") {
+                                    obj = FormatFunction(indent, obj);
+                                    html += FormatLiteral(obj, "", comma, indent, isArray, "Function");
+                                } else {
+                                    if (type == "undefined") {
+                                        html += FormatLiteral("undefined", "", comma, indent, isArray, "Null");
+                                    } else {
+                                        html += FormatLiteral(obj, '"', comma, indent, isArray, "String");
+                                    }
+                                }
+                            }
+                        }
+                    }
+                }
+            }
+            return html;
+        };
+ 
+        function FormatLiteral(literal, quote, comma, indent, isArray, style) {
+            if (typeof literal == "string") {
+                literal = literal.split("<").join("<").split(">").join(">");
+            }
+            var str = "" + quote + literal + quote + comma + "";
+            if (isArray) {
+                str = GetRow(indent, str);
+            }
+            return str;
+        }
+        function FormatFunction(indent, obj) {
+            var tabs = "";
+            for (var i = 0; i < indent; i++) {
+                tabs += "    ";
+            }
+            var funcStrArray = obj.toString().split("\n");
+            var str = "";
+            for (var i = 0; i < funcStrArray.length; i++) {
+                str += ((i == 0) ? "": tabs) + funcStrArray[i] + "\n";
+            }
+            return str;
+        }
+        function GetRow(indent, data, isPropertyContent) {
+            var tabs = "";
+            for (var i = 0; i < indent && !isPropertyContent; i++) {
+                tabs += "    ";
+            }
+            if (data != null && data.length > 0 && data.charAt(data.length - 1) != "\n") {
+                data = data + "\n";
+            }
+            return tabs + data;
+        };
+
+    
+    
+
+ +

结果

+

+
+ diff --git a/Task/jdCookie.js b/Task/jdCookie.js index 3063efcefa..929040fec3 100644 --- a/Task/jdCookie.js +++ b/Task/jdCookie.js @@ -18,9 +18,10 @@ if (process.env.JD_COOKIE) { } else { CookieJDs = process.env.JD_COOKIE.split(); } - console.log(`\n==================脚本执行来自 github action=====================\n`) - console.log(`==================脚本执行-国际标准时间(UTC):${new Date().toLocaleString()}=====================\n`) - console.log(`==================脚本执行- 北京时间(UTC+8):${new Date(new Date().getTime() + 8 * 60 * 60 * 1000).toLocaleString()}=====================\n`) + console.log(`\n==================== 共有${CookieJDs.length}个京东账号Cookie =========`); + console.log(`\n================== 脚本执行来自 github action =====================\n`) + console.log(`================== 脚本执行-国际标准时间(UTC):${new Date().toLocaleString()} =====================\n`) + console.log(`================== 脚本执行- 北京时间(UTC+8):${new Date(new Date().getTime() + 8 * 60 * 60 * 1000).toLocaleString()} =====================\n`) } for (let i = 0; i < CookieJDs.length; i++) { const index = (i + 1 === 1) ? '' : (i + 1); diff --git a/Task/jukan.js b/Task/jukan.js new file mode 100644 index 0000000000..501cf658e2 --- /dev/null +++ b/Task/jukan.js @@ -0,0 +1,619 @@ +/* +聚看点签到任务,不支持Actions跑阅读任务,其他任务可运行 +打开'我的'获取Cookie +更新时间: 2021-01-03 12:03 +https:\/\/www\.xiaodouzhuan\.cn\/jkd\/newMobileMenu\/infoMe\.action url script-request-body jukan.js + +可自动提现,提现需填写微信真实姓名,设置提现金额,默认30,此设置可以boxjs内完成,也可本地配置 + +hostname = www.xiaodouzhuan.cn +~~~~~~~~~~~~~~~~ + +*/ +const $ = new Env('聚看点') +const drawcash = $.getdata('jukan_cash') || "30" //提现金额 +const wxname = $.getdata('jukan_name') || ""//微信真实名字,可以在双引号内填入 +let CookieArr=[],BodyArr=[]; +let bodys = $.getdata('jukan_body') +let signtimes = $.getdata('jukan_times') +let cashout = $.getdata('jukan_out')|| false +let UA = 'JuKanDian/5.6.5 (iPhone; iOS 14.2; Scale/3.00)' +let taskresult = "",sumnotify =""; + +if ($.isNode()) { + if (process.env.JUKAN_BODY && process.env.JUKAN_BODY.indexOf('&') > -1) { + JKbody = process.env.JUKAN_BODY.split('&'); + } + else if (process.env.JUKAN_BODY && process.env.JUKAN_BODY.indexOf('\n') > -1) { + JKbody = process.env.JUKAN_BODY.split('\n'); + } else { + JKbody = process.env.JUKAN_BODY.split() + } + Object.keys(JKbody).forEach((item) => { + if (JKbody[item]) { + BodyArr.push(JKbody[item]) + } + }) +} else if (bodys.indexOf('&')>-1){ + Object.keys(bodys.split('&')).forEach((item) => { + BodyArr.push(bodys.split('&')[item]) + }) +} else { + BodyArr.push(bodys) +} + +if ($.isNode()) { + console.log(`============ 脚本执行-国际标准时间(UTC):${new Date().toLocaleString()} =============\n`) + console.log(`============ 脚本执行-北京时间(UTC+8):${new Date(new Date().getTime() + 8 * 60 * 60 * 1000).toLocaleString()} =============\n`) +} + +if (typeof $request !== 'undefined') { + if ($request && $request.method != `OPTIONS`) { + const bodyVal = $request.body + if(bodyVal)$.setdata(bodyVal,'jukan_body') + $.log(`bodyVal:${bodyVal}`) + $.msg($.name,"获取请求成功") + $.done() + } +} else { +!(async() => { + if (!BodyArr[0]) { + console.log($.name, '【提示】请把聚看点Cookie填入Github 的 Secrets 中,请以&或者换行隔开') + return; + } + console.log(`您共提供${BodyArr.length}个聚看点账号Cookie\n————————————————————————————————————\n`) + for (let i = 0; i < BodyArr.length; i++) { + if (BodyArr[i]) { + bodyval = BodyArr[i] + ID = decodeURIComponent(bodyval).match(/"openid" : "(\w+)"/)[1] + apptoken = decodeURIComponent(bodyval).match(/"apptoken" : "(\w+)"/)[1] + appVersion = decodeURIComponent(bodyval).match(/"appversion" : "(.*)"/)[1] + cookieval = `xz_jkd_appkey=${ID}!iOS!${appVersion}` + times = Date.parse(new Date())/1000 + $.index = i + 1; + console.log("聚看点账号"+$.index+"任务开始\n") + await sign(); + await getsign(); + await stimulate(); + await TimeBox(); + await userinfo(); + await LuckDrawLevel(); + for(boxtype of [1,2]){ + await $.wait(1000); + await BoxProfit(boxtype) + } + for ( x =18;x<32;++x){ + await Stimulate(x) + } + if (cashout==true&&curcash >= drawcash && wxname){ + await realname(); + //await Withdraw() //实名未通过,强制提现,可取消此注释,不保证成功 + } + if (signtimes&&signtimes<5){ + await WelfareCash(); + } + if(new Date().getTimezoneOffset() != '-480'){ + continue + } else { + await artTotal() +} + if ((150-artcount) == 0&&(50-videocount) ==0){ + $.msg($.name+" 昵称:"+userName, $.sub, $.desc+"<今日阅读任务已完成>",{'media-url': calendarpic }) + } + $.log("\n"+ $.name+"账号"+$.index+" : "+userName+ " 本次运行任务已结束\n~~~~~~~~~~~~~~~~~~\n") + } + } +})() + .catch((e) => $.logErr(e)) + .finally(() => $.done()) +} +//签到 +function sign() { + return new Promise((resolve, reject) =>{ + let profiturl = { + url: `https://www.xiaodouzhuan.cn/jkd/account/homeSignAccount.action`, + headers: {Cookie:cookieval,'User-Agent':UA}, body: bodyval + } + $.post(profiturl, async(error, resp, data) => { + //$.log(data+"\n") + try{ + let sign_res = JSON.parse(data) + if (sign_res.ret == "ok"){ + calendarpic = sign_res.calendar_pic + //$.log("签到收益: +"+`calendar_pic`) + } else { + $.log(sign_res.rtn_msg) + } + } catch (e) { + $.logErr(e, data) + } finally { + resolve(); + } + }) + }) +} + +function getsign() { + return new Promise((resolve, reject) =>{ + let signurl = { + url: `https://www.xiaodouzhuan.cn/jkd/user/usersign.action`, + headers: {Cookie:cookieval,'User-Agent':UA}, + body: bodyval + } + $.post(signurl, async(error, response, data) => { + try{ + let get_sign = JSON.parse(data) + //$.log(data) + if (get_sign.ret == "ok"){ + signtimes = get_sign.signDays + if(signtimes) $.setdata(signtimes, 'jukan_times') + $.sub = `签到成功🎉` + $.desc = `签到收益: +${get_sign.todaySignProfit}${get_sign.todaySignProfitType}💰,明日 +${get_sign.tomorrowSignProfit}${get_sign.tomorrowSignProfitType} 已签到 ${signtimes} 天\n` ; + await signShare() + } + else if (get_sign.rtn_code == "R-ART-0008"){ + $.sub = get_sign.rtn_msg + $.desc = `` + $.log($.sub) + } + else { + $.sub = `签到失败❌` + $.desc = `说明: `+ get_sign.rtn_msg + $.msg($.name,$.sub,$.desc) + $.done() + } + } catch (e) { + $.logErr(e, data) + } finally { + resolve(); + } + }) + }) +} + +function signShare() { + return new Promise((resolve, reject) =>{ + let profiturl = { + url: `https://www.xiaodouzhuan.cn/jkd/account/signShareAccount.action`, + headers: {Cookie:cookieval,'User-Agent':UA}, body: bodyval + } + $.post(profiturl, async(error, resp, data) => { + //$.log(data+"\n") + let sign_share = JSON.parse(data) + if (sign_share.ret == "ok"){ + $.log("签到分享收益: +"+sign_share.profit) + await Stimulate("23") + await invite() + } else { + $.log(sign_share.rtn_msg) + } + resolve() + }) + }) +} + + +function LuckDrawLevel() { + return new Promise((resolve, reject) =>{ + let Levelurl = { + url: `https://www.xiaodouzhuan.cn/jkd/activity/advluckdraw/getLuckDrawLevel.action`, + headers: {Cookie:cookieval,'User-Agent':UA}, body: bodyval + } + $.post(Levelurl, async(error, resp, data) => { + try { + get_drawLevel = JSON.parse(data) + //$.log(data) + if (get_drawLevel.ret == "ok"){ + unNum = get_drawLevel.data.unFinishNum + if(unNum>0){ + $.log("转盘任务剩余"+unNum+`次,去转盘任务`) + for(k=0;k<10&&k{ + let DrawGoldurl = { + url: `https://www.xiaodouzhuan.cn/jkd/activity/advluckdraw/getLuckDrawGold.action`, + headers: {Cookie:cookieval,'User-Agent':UA}, body: bodyval + } + $.post(DrawGoldurl, async(error, resp, data) => { + //$.log(data+"\n") + let get_drawGold = JSON.parse(data) + if (get_drawGold.ret == "ok"){ + $.log(get_drawGold.return_msg) + await LuckProfit() + } else if (get_drawGold.ret =="failed"){ + $.log(get_drawGold.rtn_msg +` 转盘抽奖失败`) + } + resolve() + }) + }) +} + +function LuckBox(x) { + return new Promise((resolve, reject) =>{ + let Boxurl = { + url: `https://www.xiaodouzhuan.cn/jkd/activity/advluckdraw/getLuckDrawBox.action`, + headers: {Cookie:cookieval,'User-Agent':UA}, body: `num=${x}` + } + $.post(Boxurl, async(error, resp, data) => { + // $.log(data+"\n") + let Timebox = JSON.parse(data) + if (Timebox.ret == "ok"){ + $.log("时段宝箱开启成功,获取金币+"+ Timebox.data) + } else if (Timebox.ret =="failed"){ + $.log(`时段宝箱开启失败`+Timebox.return_msg) + } + resolve() + }) + }) +} + +function LuckProfit() { + return new Promise((resolve, reject) =>{ + let LuckProfiturl = { + url: `https://www.xiaodouzhuan.cn/jkd/activity/advluckdraw/getTotalLuckProfit.action`, + headers: {Cookie:cookieval,'User-Agent':UA}, body: bodyval + } + $.post(LuckProfiturl, async(error, resp, data) => { + //$.log(data+"\n") + let luckProfit = JSON.parse(data) + if (luckProfit.ret == "ok"){ + lktotalProfit = luckProfit.data.totalProfit + $.log("转盘任务成功,总计金币: "+ lktotalProfit+ luckProfit.return_msg) + } else if (luckProfit.ret =="failed"){ + $.log(`转盘抽奖失败`) + } + resolve() + }) + }) +} + +function WelfareCash() { + return new Promise((resolve, reject) =>{ + let welurl = { + url: `https://www.xiaodouzhuan.cn/jkd/activity/cashweal/noviceWelfareCash.action`, + headers: {Cookie:cookieval,'User-Agent':UA} + } + $.post(welurl, async(error, resp, data) => { + //$.log(data+"\n") + let _welfareCash = JSON.parse(data) + if (_welfareCash.ret == "ok"){ + $.log("新手福利提现: 成功") + } else { + $.log(_welfareCash.rtn_msg) + } + resolve() + }) + }) +} + +function TimeBox() { + return new Promise((resolve, reject) =>{ + let boxurl = { + url: `https://www.xiaodouzhuan.cn/jkd/account/openTimeBoxAccount.action`, + headers: {Cookie:cookieval,'User-Agent':UA}, + body: bodyval + } + $.post(boxurl, async(error, resp, data) => { + //$.log(data+"\n") + let _timebox = JSON.parse(data) + if (_timebox.ret == "ok"){ + //$.log("定时宝箱开启成功,获得收益+"+_timebox.profit + " 下次需"+_timebox.next_time+"分钟") + await $.wait(2000) + await Stimulate(_timebox.advertPopup.position) + } else { + $.log(_timebox.rtn_msg) + } + resolve() + }) + }) +} + +function realname() { + return new Promise((resolve, reject) =>{ + let realurl = { + url: `https://www.xiaodouzhuan.cn/jkd/weixin20/userWithdraw/verifyIdentity.action?realname=`+encodeURIComponent(wxname), + headers: {Cookie:cookieval} + } + $.get(realurl, async(error, resp, data) => { + let get_name = JSON.parse(data) + if (get_name.ret=="ok"){ + $.log("恭喜您,实名验证通过" + get_name.return_msg) + await Withdraw() + } else if(get_name.ret== "failed"){ + $.log("实名验证" + get_name.return_msg) + // $.msg($.name,get_name.return_msg) + } + resolve() + }) + }) +} + +//提现 +function Withdraw() { + return new Promise((resolve, reject) =>{ + let drawurl = { + url: `https://www.xiaodouzhuan.cn/jkd/weixin20/userWithdraw/userWithdrawPost.action`, + headers: {Cookie:cookieval,'User-Agent':UA,'Referer': 'https://www.xiaodouzhuan.cn/jkd/weixin20/userWithdraw/userWithdraw.action'}, body: `type=wx&sum=${sumcash}&mobile=&pid=0&accountid=&productcode=` + } + $.post(drawurl, async(error, resp, data) => { + $.log("提现"+drawcash+"元"+data+"\n") + $.desc += "提现"+drawcash+"元 "+data+"\n" + resolve() + }) + }) +} + + +function Cashstatus() { + return new Promise((resolve, reject) =>{ + let drawurl = { + url: `https://www.xiaodouzhuan.cn/jkd/weixin20/userWithdraw/userWithdrawPost.action`, + headers: {Cookie:cookieval,'User-Agent':UA} +} + $.post(drawurl, async(error, resp, data) => { + $.log("提现"+drawcash+"元"+data+"\n") + $.desc += "提现"+drawcash+"元 "+data+"\n" + resolve() + }) + }) +} + +function userinfo() { + return new Promise((resolve, reject) =>{ + let infourl = { + url: `https://www.xiaodouzhuan.cn/jkd/newMobileMenu/infoMe.action`, + headers: {Cookie:cookieval,'User-Agent':UA}, + body: bodyval + } + $.post(infourl, async(error, resp, data) => { + try{ + let get_info = JSON.parse(data) + if( get_info.ret=="ok"){ + userName = get_info.userinfo.username + sumcash = get_info.userinfo.infoMeSumCashItem.title+get_info.userinfo.infoMeSumCashItem.value + curcashtitle = get_info.userinfo.infoMeCurCashItem.title + curcash = get_info.userinfo.infoMeCurCashItem.value + gold = get_info.userinfo.infoMeGoldItem.title+": "+get_info.userinfo.infoMeGoldItem.value + $.log("昵称:"+userName+" "+gold +"\n"+sumcash + "/"+curcashtitle+curcash ) + $.sub += " "+gold + $.desc += sumcash + " ~~~~ "+curcashtitle+curcash+"\n" + } + } catch (e) { + $.logErr(e, data) + } finally { + resolve(); + } + }) + }) +} + +function artTotal() { + return new Promise((resolve, reject) =>{ + let infourl = { + url: `https://www.xiaodouzhuan.cn/jkd/weixin20/station/readAccount.action`, + headers: {Cookie:cookieval,'User-Agent':UA}, + } + $.post(infourl, async(error, resp, data) => { + try{ + artcount = data.match(/(今日奖励次数\((\d+)次\))/g)[0].match(/\d+/) + videocount = data.match(/(今日奖励次数\((\d+)次\))/g)[1].match(/\d+/) + artcoin = data.match(/gold"\>\+(\d+金币)/)[1] + videocoin = data.match(/\d+金币/g)[7] + readtotal = data.match(/gold1"\>\+(\d+金币)/)[1] + sharetotal = data.match(/\d+金币/g)[9] + $.desc += "【今日阅读统计】\n 文章: " +Number(artcount) + "次 收益: "+artcoin+"\n 视频: " +Number(videocount) + "次 收益: "+videocoin+"\n" + $.desc += "【昨日阅读统计】\n 自阅收益: " +readtotal +" 分享收益: "+sharetotal +"\n" + $.log( "当前阅读次数"+artcount+"次,视频次数"+videocount+"次\n") + if(150-artcount > 0 ){ + readbodyVal = bodyval.replace(/time%22%20%3A%20%22\d+%22/, `time%22%20%3A%20%22${times}%22%2C%20`+'%22cateid%22%20%3A%203') + await artList(readbodyVal) + } else if ( artcount == 0 ){ + $.log("今日阅读任务已完成,本次跳过") + }; + if(50-videocount > 0 ){ + readbodyVal = bodyval.replace(/time%22%20%3A%20%22\d+%22/,`time%22%20%3A%20%22${times+31000}%22%2C%20`+'%22cateid%22%20%3A%2053') + await artList(readbodyVal) + } else if ( artcount == 0 ){ + $.log("今日视频任务已完成,本次跳过") + }; + } catch (e) { + $.logErr(e, data) + } finally { + resolve(data); + } + }) + }) +} + +function artList(readbodyVal) { + return new Promise((resolve, reject) =>{ + let infourl = { + url: `https://www.xiaodouzhuan.cn/jkd/newmobile/artlist.action`, + headers: {Cookie:cookieval,'User-Agent':UA}, + body: readbodyVal + } + $.post(infourl, async(error, resp, data) => { + let get_list = JSON.parse(data) + // $.log( data) + if (get_list.ret == "ok"){ + for( lists of get_list.artlist){ + if(lists.item_type=="article"){ + art_Title = lists.art_title + artid =lists.art_id + screen_Name = lists.screen_name + $.log(" 【阅读文章】: "+art_Title +" -------- <"+screen_Name +">\n ") + await readTask(lists.art_id,"1") + } + if(lists.item_type=="video"){ + art_Title = lists.art_title + artid =lists.art_id + screen_Name = lists.screen_name + $.log(" 【观看视频】: "+art_Title +" -------- <"+screen_Name +">\n ") + await readTask(lists.art_id,"2") + } + if(taskresult == 'R-ART-1002'|| taskresult ==`R-ART-0011`){ + break + } + } + } + resolve() + }) + }) +} + + +function readTask(artid,arttype) { + return new Promise((resolve, reject) =>{ + let rewurl = { + url: `https://www.xiaodouzhuan.cn/jkd/newmobile/artDetail.action`, + headers: {Cookie:cookieval,'User-Agent':UA}, + body: `jsondata={"appid":"xzwl","channel":"IOS","relate":1,"artid":"${artid}","os":"IOS","openid":"${ID}","apptoken":"${apptoken}","appversion":"${appVersion}"}` + } + $.post(rewurl, async(error, resp, data) => { + if(resp.statusCode ==200){ + for(s=0;s<2;++s){ + $.log(` 开始第${s+1}次阅读,请等待30s\n`) + await $.wait(30000) + await finishTask(artid,arttype) + } + } else { + $.log("阅读失败: "+data) + } + resolve() + }) + }) +} + +function finishTask(artid,arttype) { + return new Promise((resolve, reject) =>{ + let finishurl = { + url: `https://www.xiaodouzhuan.cn/jkd/account/readAccount.action`, + headers: {Cookie:cookieval,'User-Agent':UA}, + body: `jsondata={"appid":"xzwl","read_weal":0,"paytype":"${arttype}","securitykey":"","channel":"iOS","time":"${times}","apptoken":"${apptoken}","appversion":"${appVersion}","openid":"${ID}","os":"iOS","artid":${artid},"accountType":"0","readmodel":"1"}` + } + $.post(finishurl, async(error, response, data) => { + //$.log(data+"\n") + let do_read = JSON.parse(data) + taskresult = do_read.rtn_code + if (do_read.ret == "ok"){ + $.log(" 获得收益: +"+do_read.profit +"\n") + } else { + $.log(do_read.rtn_msg) + } + resolve() + }) + }) +} + + +function stimulate() { + return new Promise((resolve, reject) =>{ + let Advurl = { + url: `https://www.xiaodouzhuan.cn/jkd/newmobile/stimulateAdv.action`, + headers: {Cookie:cookieval,'User-Agent':UA}, + body: `jsondata={"read_weal":"0","appid":"xzwl", "position":"17","time" : "${times}", "apptoken" : "${apptoken}","appversion":"${appVersion}","openId":"${ID}","os":"iOS","channel":"iOS"}` + } + $.post(Advurl, async(error, resp, data) => { + //$.log(data+"\n") + let _Adv = JSON.parse(data) + if (_Adv.ret == "ok"&&_Adv.status==1){ + $.log("视频"+ _Adv.videoType+"获得红包: +"+_Adv.rewardAmount+_Adv.rewardName) + await $.wait(1000) + await Stimulate("17") + } else { + $.log("视频广告红包,"+ _Adv.message) + } + resolve() + }) + }) +} + +//激励视频 +function Stimulate(position) { + return new Promise((resolve, reject) =>{ + let stimurl = { + url: `https://www.xiaodouzhuan.cn/jkd/account/stimulateAdvAccount.action`, + headers: {Cookie:cookieval,'User-Agent':UA}, + body: `jsondata={"read_weal":"0","appid":"xzwl", "position" : ${position},"time" : "${times}","apptoken":"${apptoken}","appversion":"5.6.5","openid":"${ID}","os":"iOS","channel":"iOS"}` + } + $.post(stimurl, async(error, resp, data) => { + //$.log(data+"\n") + let do_stim = JSON.parse(data) + if(typeof do_stim.profit_title == "undefined"){ + } else { + $.log( do_stim.profit_title+ "position"+": "+position+" 获得收益 +"+ do_stim.profit) + await $.wait(2000) + } + resolve() + }) + }) +} + +function BoxProfit(boxtype) { + return new Promise((resolve, reject) =>{ + let profiturl = { + url: `https://www.xiaodouzhuan.cn/jkd/task/getTaskBoxProfit.action`, + headers: {Cookie:cookieval,'User-Agent':UA}, body: `box_type=${boxtype}` + } + $.post(profiturl, async(error, resp, data) => { + //$.log(data+"\n") + let do_box = JSON.parse(data) + if (do_box.ret == "ok"&&do_box.profit>0){ + $.log("计时宝箱获得收益: +"+do_box.profit) + //$.desc += "【计时宝箱】+"+do_box.profit+"金币\n" + position = do_box.advertPopup.position + await Stimulate(position) + // $.log(position) + } + else if (do_box.rtn_code=='TAS-A-1'){ + $.log("计时金币"+do_box.rtn_msg) + } + resolve() + }) + }) +} + + +function invite() { + let rewurl = { + url: `https://www.xiaodouzhuan.cn/jkd/weixin20/member/bindTeacher.action?teacherCode=24222820`, + headers: {Cookie:cookieval}, + body: bodyval + } + $.get(rewurl, (error, resp, data) => { + //$.log(data) + }) +} + + +function Env(t,e){class s{constructor(t){this.env=t}send(t,e="GET"){t="string"==typeof t?{url:t}:t;let s=this.get;return"POST"===e&&(s=this.post),new Promise((e,i)=>{s.call(this,t,(t,s,r)=>{t?i(t):e(s)})})}get(t){return this.send.call(this.env,t)}post(t){return this.send.call(this.env,t,"POST")}}return new class{constructor(t,e){this.name=t,this.http=new s(this),this.data=null,this.dataFile="box.dat",this.logs=[],this.isMute=!1,this.isNeedRewrite=!1,this.logSeparator="\n",this.startTime=(new Date).getTime(),Object.assign(this,e),this.log("",`\ud83d\udd14${this.name}, \u5f00\u59cb!`)}isNode(){return"undefined"!=typeof module&&!!module.exports}isQuanX(){return"undefined"!=typeof $task}isSurge(){return"undefined"!=typeof $httpClient&&"undefined"==typeof $loon}isLoon(){return"undefined"!=typeof $loon}toObj(t,e=null){try{return JSON.parse(t)}catch{return e}}toStr(t,e=null){try{return JSON.stringify(t)}catch{return e}}getjson(t,e){let s=e;const i=this.getdata(t);if(i)try{s=JSON.parse(this.getdata(t))}catch{}return s}setjson(t,e){try{return this.setdata(JSON.stringify(t),e)}catch{return!1}}getScript(t){return new Promise(e=>{this.get({url:t},(t,s,i)=>e(i))})}runScript(t,e){return new Promise(s=>{let i=this.getdata("@chavy_boxjs_userCfgs.httpapi");i=i?i.replace(/\n/g,"").trim():i;let r=this.getdata("@chavy_boxjs_userCfgs.httpapi_timeout");r=r?1*r:20,r=e&&e.timeout?e.timeout:r;const[o,h]=i.split("@"),a={url:`http://${h}/v1/scripting/evaluate`,body:{script_text:t,mock_type:"cron",timeout:r},headers:{"X-Key":o,Accept:"*/*"}};this.post(a,(t,e,i)=>s(i))}).catch(t=>this.logErr(t))}loaddata(){if(!this.isNode())return{};{this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(this.dataFile),e=this.path.resolve(process.cwd(),this.dataFile),s=this.fs.existsSync(t),i=!s&&this.fs.existsSync(e);if(!s&&!i)return{};{const i=s?t:e;try{return JSON.parse(this.fs.readFileSync(i))}catch(t){return{}}}}}writedata(){if(this.isNode()){this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(this.dataFile),e=this.path.resolve(process.cwd(),this.dataFile),s=this.fs.existsSync(t),i=!s&&this.fs.existsSync(e),r=JSON.stringify(this.data);s?this.fs.writeFileSync(t,r):i?this.fs.writeFileSync(e,r):this.fs.writeFileSync(t,r)}}lodash_get(t,e,s){const i=e.replace(/\[(\d+)\]/g,".$1").split(".");let r=t;for(const t of i)if(r=Object(r)[t],void 0===r)return s;return r}lodash_set(t,e,s){return Object(t)!==t?t:(Array.isArray(e)||(e=e.toString().match(/[^.[\]]+/g)||[]),e.slice(0,-1).reduce((t,s,i)=>Object(t[s])===t[s]?t[s]:t[s]=Math.abs(e[i+1])>>0==+e[i+1]?[]:{},t)[e[e.length-1]]=s,t)}getdata(t){let e=this.getval(t);if(/^@/.test(t)){const[,s,i]=/^@(.*?)\.(.*?)$/.exec(t),r=s?this.getval(s):"";if(r)try{const t=JSON.parse(r);e=t?this.lodash_get(t,i,""):e}catch(t){e=""}}return e}setdata(t,e){let s=!1;if(/^@/.test(e)){const[,i,r]=/^@(.*?)\.(.*?)$/.exec(e),o=this.getval(i),h=i?"null"===o?null:o||"{}":"{}";try{const e=JSON.parse(h);this.lodash_set(e,r,t),s=this.setval(JSON.stringify(e),i)}catch(e){const o={};this.lodash_set(o,r,t),s=this.setval(JSON.stringify(o),i)}}else s=this.setval(t,e);return s}getval(t){return this.isSurge()||this.isLoon()?$persistentStore.read(t):this.isQuanX()?$prefs.valueForKey(t):this.isNode()?(this.data=this.loaddata(),this.data[t]):this.data&&this.data[t]||null}setval(t,e){return this.isSurge()||this.isLoon()?$persistentStore.write(t,e):this.isQuanX()?$prefs.setValueForKey(t,e):this.isNode()?(this.data=this.loaddata(),this.data[e]=t,this.writedata(),!0):this.data&&this.data[e]||null}initGotEnv(t){this.got=this.got?this.got:require("got"),this.cktough=this.cktough?this.cktough:require("tough-cookie"),this.ckjar=this.ckjar?this.ckjar:new this.cktough.CookieJar,t&&(t.headers=t.headers?t.headers:{},void 0===t.headers.Cookie&&void 0===t.cookieJar&&(t.cookieJar=this.ckjar))}get(t,e=(()=>{})){t.headers&&(delete t.headers["Content-Type"],delete t.headers["Content-Length"]),this.isSurge()||this.isLoon()?(this.isSurge()&&this.isNeedRewrite&&(t.headers=t.headers||{},Object.assign(t.headers,{"X-Surge-Skip-Scripting":!1})),$httpClient.get(t,(t,s,i)=>{!t&&s&&(s.body=i,s.statusCode=s.status),e(t,s,i)})):this.isQuanX()?(this.isNeedRewrite&&(t.opts=t.opts||{},Object.assign(t.opts,{hints:!1})),$task.fetch(t).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>e(t))):this.isNode()&&(this.initGotEnv(t),this.got(t).on("redirect",(t,e)=>{try{if(t.headers["set-cookie"]){const s=t.headers["set-cookie"].map(this.cktough.Cookie.parse).toString();s&&this.ckjar.setCookieSync(s,null),e.cookieJar=this.ckjar}}catch(t){this.logErr(t)}}).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>{const{message:s,response:i}=t;e(s,i,i&&i.body)}))}post(t,e=(()=>{})){if(t.body&&t.headers&&!t.headers["Content-Type"]&&(t.headers["Content-Type"]="application/x-www-form-urlencoded"),t.headers&&delete t.headers["Content-Length"],this.isSurge()||this.isLoon())this.isSurge()&&this.isNeedRewrite&&(t.headers=t.headers||{},Object.assign(t.headers,{"X-Surge-Skip-Scripting":!1})),$httpClient.post(t,(t,s,i)=>{!t&&s&&(s.body=i,s.statusCode=s.status),e(t,s,i)});else if(this.isQuanX())t.method="POST",this.isNeedRewrite&&(t.opts=t.opts||{},Object.assign(t.opts,{hints:!1})),$task.fetch(t).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>e(t));else if(this.isNode()){this.initGotEnv(t);const{url:s,...i}=t;this.got.post(s,i).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>{const{message:s,response:i}=t;e(s,i,i&&i.body)})}}time(t){let e={"M+":(new Date).getMonth()+1,"d+":(new Date).getDate(),"H+":(new Date).getHours(),"m+":(new Date).getMinutes(),"s+":(new Date).getSeconds(),"q+":Math.floor(((new Date).getMonth()+3)/3),S:(new Date).getMilliseconds()};/(y+)/.test(t)&&(t=t.replace(RegExp.$1,((new Date).getFullYear()+"").substr(4-RegExp.$1.length)));for(let s in e)new RegExp("("+s+")").test(t)&&(t=t.replace(RegExp.$1,1==RegExp.$1.length?e[s]:("00"+e[s]).substr((""+e[s]).length)));return t}msg(e=t,s="",i="",r){const o=t=>{if(!t)return t;if("string"==typeof t)return this.isLoon()?t:this.isQuanX()?{"open-url":t}:this.isSurge()?{url:t}:void 0;if("object"==typeof t){if(this.isLoon()){let e=t.openUrl||t.url||t["open-url"],s=t.mediaUrl||t["media-url"];return{openUrl:e,mediaUrl:s}}if(this.isQuanX()){let e=t["open-url"]||t.url||t.openUrl,s=t["media-url"]||t.mediaUrl;return{"open-url":e,"media-url":s}}if(this.isSurge()){let e=t.url||t.openUrl||t["open-url"];return{url:e}}}};if(this.isMute||(this.isSurge()||this.isLoon()?$notification.post(e,s,i,o(r)):this.isQuanX()&&$notify(e,s,i,o(r))),!this.isMuteLog){let t=["","==============\ud83d\udce3\u7cfb\u7edf\u901a\u77e5\ud83d\udce3=============="];t.push(e),s&&t.push(s),i&&t.push(i),console.log(t.join("\n")),this.logs=this.logs.concat(t)}}log(...t){t.length>0&&(this.logs=[...this.logs,...t]),console.log(t.join(this.logSeparator))}logErr(t,e){const s=!this.isSurge()&&!this.isQuanX()&&!this.isLoon();s?this.log("",`\u2757\ufe0f${this.name}, \u9519\u8bef!`,t.stack):this.log("",`\u2757\ufe0f${this.name}, \u9519\u8bef!`,t)}wait(t){return new Promise(e=>setTimeout(e,t))}done(t={}){const e=(new Date).getTime(),s=(e-this.startTime)/1e3;this.log("",`\ud83d\udd14${this.name}, \u7ed3\u675f! \ud83d\udd5b ${s} \u79d2`),this.log(),(this.isSurge()||this.isQuanX()||this.isLoon())&&$done(t)}}(t,e)} diff --git a/Task/kuaishou.js b/Task/kuaishou.js index a1e42b5e12..85b51a68bb 100644 --- a/Task/kuaishou.js +++ b/Task/kuaishou.js @@ -1,144 +1,360 @@ /* -更新时间: 2020-09-08 11:45 - -本脚本仅适用于快手极速版签到 -获取Cookie方法: -1.将下方[rewrite_local]和[MITM]地址复制的相应的区域 -下 -2.APP登陆账号后,以下方法获取Cookie -打开设置页面:"积分兑好礼" - -3.非专业人士制作,欢迎各位大佬提出宝贵意见和指导 -仅测试Quantumult x,Surge、Loon自行测试 -by Macsuny -感谢 -@Chavy -@Nobyda -~~~~~~~~~~~~~~~~ - -Surge 4.0 : -[Script] -快手极速版 = type=cron,cronexp=35 5 0 * * *,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/kuaishou.js,script-update-interval=0 - -快手极速版 = type=http-request,pattern=https:\/\/nebula\.kuaishou\.com\/nebula\/task\/earning\?,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/kuaishou.js - -~~~~~~~~~~~~~~~~ -Loon 2.1.0+ -[Script] -# 本地脚本 -cron "04 00 * * *" script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/kuaishou.js, enabled=true, tag=快手 - -http-request https:\/\/nebula\.kuaishou\.com\/nebula\/task\/earning\? script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/kuaishou.js - ------------------ - -QX 1.0.7+ : -[task_local] -0 9 * * * kuaishou.js - -[rewrite_local] - -https:\/\/nebula\.kuaishou\.com\/nebula\/task\/earning\? url script-request-header kuaishou.js - -~~~~~~~~~~~~~~~~ - -hostname = nebula.kuaishou.com +更新时间: 2021-02-21 10:15 +赞赏:快手邀请码`774010415`,农妇山泉 -> 有点咸,万分感谢; +本脚本仅适用于快手双版本签到,仅支持正式版获取多Cookie,建议使用正式版获取Cookie,点击视频页悬浮红包,或者进入设置,点击"积分兑好礼"即可; +本脚本仅在签到成功时通知; +兼容Nodejs,把获取的Cookie填入KS_TOKEN,多账号用"&"分开 +*/ -~~~~~~~~~~~~~~~~ +const $ = new Env('快手视频') +let cookieArr = []; +let ks_tokens = $.getdata('cookie_ks'); +const notify = $.isNode() ? require('./sendNotify') : ''; +const nebulaCash = $.getdata('cash_nebulaks')||"10"; +const cashType = $.getdata('tpcash_nebula')||"ALIPAY"; -*/ -const logs = 0 //日志开关 -const $ = new Env('快手极速版') -const cookieVal = $.getdata('cookie_ks'); let isGetCookie = typeof $request !== 'undefined' - if (isGetCookie) { - GetCookie() + GetCookie(); + $.done() } else { - !(async() => { - await sign(); - await signifo(); - await info() +if (!$.isNode() && ks_tokens.indexOf('&') == -1) { + cookieArr.push(ks_tokens) +} else { + if ($.isNode()) { + if (process.env.KS_TOKEN && process.env.KS_TOKEN.indexOf('&') > -1) { + ks_tokens = process.env.KS_TOKEN.split('&') + } else { + ks_tokens = [process.env.KS_TOKEN] + }; + } else if (!$.isNode() && ks_tokens.indexOf('&') > -1) { + ks_tokens = ks_tokens.split('&') + } + Object.keys(ks_tokens).forEach((item) =>{ + if (ks_tokens[item]) { + cookieArr.push(ks_tokens[item]) + } + }) +} +!(async() => { + if(!cookieArr[0]){ + $.msg($.name, '【提示】🉐登录快手pp获取cookie',"", {"open-url": "https://live.kuaishou.com/fission/offkwai/index?cc=share_copylink&kpf=IPHONE&traceId=27&fid=1570609569&code=3429390431&shareMethod=token&kpn=KUAISHOU&subBiz=INVITE_CODE&shareId=1000517297081&shareToken=X-1oTjAy1OkMhgQk_AO&platform=copylink&shareMode=app&shareObjectId=3429390431"}); + return + } + timeZone = new Date().getTimezoneOffset() / 60; + timestamp = Date.now()+ (8+timeZone) * 60 * 60 * 1000; + bjTime = new Date(timestamp).toLocaleString('zh',{hour12:false,timeZoneName: 'long'}) + console.log(`\n === 脚本执行 ${bjTime} ===\n`); + console.log(` === 共 ${cookieArr.length}个 账号 === `) + for (let i = 0; i < cookieArr.length; i++) { + if (cookieArr[i]) { + cookieVal = cookieArr[i]; + $.index = i + 1; + console.log(`\n------------------------\n\n开始【快手视频账号${$.index}】\n`) + await nebulaInfo(); + await nebulaPopup(); + await formalCenter(); + await formalSign(); + if(offici_code !== 100119){ + await formalinfo(); + }; + $.desc = `【正式版】:\n `+offic_info+"\n "+offic_sign +'\n' + $.desc += `【极速版】:\n `+speed_rewards+"\n "+speed_info; + if(offici_code==1){ + $.msg($.name+" 昵称:"+nickname,"",$.desc); + await notify.sendNotify($.name+ " " +nickname,$.desc) + } else { + $.log( "~~~~~~~~~~~~~~~~~\n 昵称:" +nickname+"\n"+ $.desc) + } + } + } })() .catch((e) => $.logErr(e)) .finally(() => $.done()) } -function GetCookie() { - if ($request.headers) { - var CookieValue = $request.headers['Cookie']; - - if ($.getdata('cookie_ks') != (undefined || null)) { - if ($.getdata('cookie_ks') != CookieValue) { - var cookie = $.setdata(CookieValue, 'cookie_ks'); - if (!cookie) { - $.msg("更新" + $.name + "Cookie失败‼️", "", ""); - $.log(`[${$.name}] 获取Cookie: 失败`); + +function formalHost(api,body){ + return { + url: 'https://activity.m.kuaishou.com/rest/wd/taskCenter/'+api, + headers:{ + 'Host': 'activity.m.kuaishou.com', + 'Cookie': cookieVal, + 'Content-Type': 'application/json;charset=utf-8', + 'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 Kwai/9.0.50.4936 CT/0 WebViewType/WK NetType/WIFI Yoda/2.3.7-rc5 TitleHT/44 StatusHT/20' + }, + body: body + } +} + +function formalCenter() { + return new Promise((resolve, reject) =>{ + $.post(formalHost('lowActive/module/list', '{"bizId":29,"configId":1}'), async(error, resp, data) =>{ + let central = JSON.parse(data); +$.log("\n----------------------------------------\n\n现在开始正式版任务") + try { + if (central.result == 1) { + for (lists of central.modules) { + Id = lists.moduleId, + moduleDesc = lists.moduleDesc; + $.log("\n"+moduleDesc); + for (tasks of lists.tasks) { + //$.log(JSON.stringify(tasks,null,2)); + status = tasks.status, + bizId = tasks.bizId, + tasktoken = tasks.token, + eventId = tasks.eventId, + schemeText = tasks.schemeText + taskName = tasks.reward.rewardName; + if (status == 5) { + $.log(taskName + " " + tasks.schemeText) + } else if (status == 2) { + $.log(taskName + schemeText); + if (Id == "1123") { + await formalSign(); + break + } else if (Id == "1176") { + //$.log(taskName) + await getReward(); + break + } + } else if (Id == "1749"){ + if(status == 4){ + await openbox(tasktoken, eventId) + } else if(status == 1){ + $.log(tasks.reward.rewardName+",时间未达到") + } + } + } + } + } + } catch(e) { + $.log("领取金币失败\n" + e + JSON.stringify(result, null, 2)) + } finally { + resolve() + } + }) + }) +} + +function openbox(tokens, eventId) { + return new Promise((resolve, reject) =>{ + $.post(formalHost('task/report', `{"bizId": 29,"taskToken": "${tokens}","eventId": "${eventId}","eventValue": 1}`), (error, resp, data) =>{ + let result = JSON.parse(data); + try { + //$.log(JSON.stringify(result,null,2)) + if (result.result == 1) { + rewards = result.reward.rewardCount, + boxname = result.dialog.title, + $.desc += "【" + boxname + "】+" + rewards + " " + result.dialog.closeBubble; + $.log(boxname + "领取金币" + rewards + "," + result.dialog.secondDesc) } else { - $.msg("更新" + $.name + "Cookie成功 🎉", "", ""); - $.log(`[${$.name}] 获取Cookie: 成功, Cookie: ${CookieValue}`) + $.log(boxname + result.error_msg) } + } catch(e) { + $.log("领取金币失败\n" + JSON.stringify(result, null, 2)) + } finally { + resolve() } - } else { - var cookie = $.setdata(CookieValue, 'cookie_ks'); - if (!cookie) { - $.msg("首次写入" + $.name + "Cookie失败‼️", "", ""); - } else { - $.msg("首次写入" + $.name + "Cookie成功 🎉", "", ""); + }) + }) +} + +function formalSign() { + return new Promise((resolve, reject) => { + $.post(formalHost('task/signIn','{"bizId": 29}'), (error, response, data) => { + let formalSign_res = JSON.parse(data) + offici_code = formalSign_res.result + if(offici_code == 100111){ + offic_sign = `签到结果: ${formalSign_res.error_msg}`; + $.log(`错误信息: ${formalSign_res.error_msg}`); + return + } else if(offici_code == 100136){ + offic_sign = `签到结果: ${formalSign_res.error_msg}`; + $.log(""+formalSign_res.error_msg) + } else if(offici_code == 1){ + offic_sign = `签到结果: ✅ +${formalSign_res.reward.rewardCount} 积分` + } + resolve() + }) + }) + } + +function getReward() { + return new Promise((resolve, reject) =>{ + $.post(formalHost('task/appStartup/reward', '{"bizId": 29}'), (error, response, data) =>{ + let reward_res = JSON.parse(data); + //moduleDesc = reward_res.appStartupModule.moduleDesc; + if (data.indexOf('surpriseRewardCount') > -1) { + surpriseReward = reward_res.reward.surpriseRewardCount + } + switch (reward_res.rewardSuccess) { + case true: + $.log("获得积分" + reward_res.reward.rewardCount + surpriseReward ? "现金奖励" + surpriseReward / 100 + "元": ""); + break; + case false: + //$.log(moduleDesc + "未完成 " + schemeText); + break; + default: + $.log('前面的条件不满足'); + break; } + resolve() + }) + }) +} + + +function formalinfo() { + return new Promise((resolve, reject) =>{ + infourl = { + url: 'https://zt.gifshow.com/rest/zt/encourage/account/summary/withKscoinTrial?kpn=KUAISHOU&subBiz=lowActiveUserTaskEncourage', + headers: { + Cookie: cookieVal, + 'Content-Type': 'application/json;charset=utf-8' + }, } - } else { - $.msg("写入" + $.name + "Cookie失败‼️", "", "配置错误, 无法读取请求头, "); - } -$.done() + $.get(infourl, async(error, resp, data) =>{ + + let _info = JSON.parse(data); + if (_info.result == 1) { + offic_info = `积分: ${_info.data.accounts[0].displayBalance}积分 现金: ${_info.data.accounts[1].displayBalance}元` + } + resolve() + }) + }) } -function sign() { +function nebulaSign() { return new Promise((resolve, reject) => { - let signurl = { - url: 'https://nebula.kuaishou.com/rest/n/nebula/sign/sign', - headers: {Cookie: cookieVal}} - $.get(signurl, (error, response, data) => { - if(logs) $.log(`${$.name}, data: ${data}`) - let result = JSON.parse(data) - if(result.result == 10007){ - subTitle = `签到结果: ${result.error_msg}` - $.msg($.name,subTitle,'')} - if(logs) $.log(`错误代码: ${result.result}, 返回信息: ${result.error_msg}`) - }) - resolve() + $.get(nebulaHost('sign/sign'), async(error, response, data) => { + let speed_res = JSON.parse(data); + speed_code = speed_res.result + if(speed_code == 10007){ + speed_sign = `签到结果: ${speed_res.error_msg}`; + $.msg($.name,speed_sign,''); + $.log(`错误信息: ${speed_res.error_msg}`) + $.done() + } else if(speed_code == 10901){ + speed_sign = `签到结果: ${speed_res.error_msg}` + } else if(speed_code == 1){ + speed_sign = `签到结果: ${speed_res.data.toast}` + if(parseInt(nebulacash) > nebulaCash){ + await nebulaWithdraw() + } + } + $.log(speed_sign) + resolve() + }) }) } -function signifo() { + +function nebulaPopup() { return new Promise((resolve, reject) => { - earnurl = { - url: 'https://nebula.kuaishou.com/rest/n/nebula/sign/query', - headers: {Cookie: cookieVal}} - $.get(earnurl, (error, response, data) => { - if(logs)$.log(`${$.name}, data: ${data}`) - let result = JSON.parse(data) - if (result.data.nebulaSignInPopup.button == '立即签到'){ - detail = `签到成功: ${result.data.nebulaSignInPopup.subTitle}, ${result.data.nebulaSignInPopup.title}` - } else if (result.data.nebulaSignInPopup.button == '好的'){ - detail = `重复签到: ${result.data.nebulaSignInPopup.subTitle}, ${result.data.nebulaSignInPopup.title}` + $.get(nebulaHost('sign/query'), (error, resp, data) => { + let result = JSON.parse(data); + if (result.result == '1'){ + speed_info = `${result.data.nebulaSignInPopup.subTitle}, ${result.data.nebulaSignInPopup.title}\n` } resolve() }) }) } -function info() { +function nebulaInfo() { return new Promise((resolve, reject) => { - let reurl = {url:'https://nebula.kuaishou.com/rest/n/nebula/activity/earn/overview', - headers: {Cookie:cookieVal}} - $.get(reurl, (error, response, data) =>{ - if(logs)$.log(`${$.name}, data: ${data}`) - let result = JSON.parse(data) + $.get(nebulaHost('activity/earn/overview'), async(error, response, data) =>{ + let result = JSON.parse(data); if (result.result == 1) { - subTitle = `现金收益: 💵${result.data.allCash}元 金币收益: 💰${result.data.totalCoin}` + nebulacash = result.data.allCash, + nickname = result.data.userData.nickname; + $.log("************ 昵称: "+nickname+" **********\n\n开始极速版任务\n"); + speed_rewards = '积分: '+result.data.totalCoin+'积分 现金: '+nebulacash+'元'; + for(nebulaTask of result.data.dailyTasks){ + taskName = nebulaTask.name + taskid = nebulaTask.id + $.log("去"+taskName) + if( nebulaTask.status!==1){ + } else { + if( taskid == 5){ +if(nebulaTask.extParam.todayIsSigned==false){ + await nebulaSign() + } else { + speed_sign = nebulaTask.desc + } + } else if(taskid == 3){ + await bdinvet(); + } + $.log(nebulaTask.desc+"\n"); + } + } + } + resolve() + }) + }) + } + +function nebulaWithdraw() { + return new Promise((resolve, reject) => { + $.post(nebulaHost('outside/withdraw/apply',`{"channel":"${cashType}","amount":${nebulacash}}`), (error, resp, data) =>{ + let result = JSON.parse(data); + if (result.result == 1) { + $.msg($.name,"极速版提现成功,提现") } - $.msg($.name,subTitle,detail) + else { + $.log(result.error_msg) + } resolve() - }) - }) + }) + }) } - -function Env(t,e){class s{constructor(t){this.env=t}send(t,e="GET"){t="string"==typeof t?{url:t}:t;let s=this.get;return"POST"===e&&(s=this.post),new Promise((e,i)=>{s.call(this,t,(t,s,r)=>{t?i(t):e(s)})})}get(t){return this.send.call(this.env,t)}post(t){return this.send.call(this.env,t,"POST")}}return new class{constructor(t,e){this.name=t,this.http=new s(this),this.data=null,this.dataFile="box.dat",this.logs=[],this.isMute=!1,this.isNeedRewrite=!1,this.logSeparator="\n",this.startTime=(new Date).getTime(),Object.assign(this,e),this.log("",`\ud83d\udd14${this.name}, \u5f00\u59cb!`)}isNode(){return"undefined"!=typeof module&&!!module.exports}isQuanX(){return"undefined"!=typeof $task}isSurge(){return"undefined"!=typeof $httpClient&&"undefined"==typeof $loon}isLoon(){return"undefined"!=typeof $loon}toObj(t,e=null){try{return JSON.parse(t)}catch{return e}}toStr(t,e=null){try{return JSON.stringify(t)}catch{return e}}getjson(t,e){let s=e;const i=this.getdata(t);if(i)try{s=JSON.parse(this.getdata(t))}catch{}return s}setjson(t,e){try{return this.setdata(JSON.stringify(t),e)}catch{return!1}}getScript(t){return new Promise(e=>{this.get({url:t},(t,s,i)=>e(i))})}runScript(t,e){return new Promise(s=>{let i=this.getdata("@chavy_boxjs_userCfgs.httpapi");i=i?i.replace(/\n/g,"").trim():i;let r=this.getdata("@chavy_boxjs_userCfgs.httpapi_timeout");r=r?1*r:20,r=e&&e.timeout?e.timeout:r;const[o,h]=i.split("@"),a={url:`http://${h}/v1/scripting/evaluate`,body:{script_text:t,mock_type:"cron",timeout:r},headers:{"X-Key":o,Accept:"*/*"}};this.post(a,(t,e,i)=>s(i))}).catch(t=>this.logErr(t))}loaddata(){if(!this.isNode())return{};{this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(this.dataFile),e=this.path.resolve(process.cwd(),this.dataFile),s=this.fs.existsSync(t),i=!s&&this.fs.existsSync(e);if(!s&&!i)return{};{const i=s?t:e;try{return JSON.parse(this.fs.readFileSync(i))}catch(t){return{}}}}}writedata(){if(this.isNode()){this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(this.dataFile),e=this.path.resolve(process.cwd(),this.dataFile),s=this.fs.existsSync(t),i=!s&&this.fs.existsSync(e),r=JSON.stringify(this.data);s?this.fs.writeFileSync(t,r):i?this.fs.writeFileSync(e,r):this.fs.writeFileSync(t,r)}}lodash_get(t,e,s){const i=e.replace(/\[(\d+)\]/g,".$1").split(".");let r=t;for(const t of i)if(r=Object(r)[t],void 0===r)return s;return r}lodash_set(t,e,s){return Object(t)!==t?t:(Array.isArray(e)||(e=e.toString().match(/[^.[\]]+/g)||[]),e.slice(0,-1).reduce((t,s,i)=>Object(t[s])===t[s]?t[s]:t[s]=Math.abs(e[i+1])>>0==+e[i+1]?[]:{},t)[e[e.length-1]]=s,t)}getdata(t){let e=this.getval(t);if(/^@/.test(t)){const[,s,i]=/^@(.*?)\.(.*?)$/.exec(t),r=s?this.getval(s):"";if(r)try{const t=JSON.parse(r);e=t?this.lodash_get(t,i,""):e}catch(t){e=""}}return e}setdata(t,e){let s=!1;if(/^@/.test(e)){const[,i,r]=/^@(.*?)\.(.*?)$/.exec(e),o=this.getval(i),h=i?"null"===o?null:o||"{}":"{}";try{const e=JSON.parse(h);this.lodash_set(e,r,t),s=this.setval(JSON.stringify(e),i)}catch(e){const o={};this.lodash_set(o,r,t),s=this.setval(JSON.stringify(o),i)}}else s=this.setval(t,e);return s}getval(t){return this.isSurge()||this.isLoon()?$persistentStore.read(t):this.isQuanX()?$prefs.valueForKey(t):this.isNode()?(this.data=this.loaddata(),this.data[t]):this.data&&this.data[t]||null}setval(t,e){return this.isSurge()||this.isLoon()?$persistentStore.write(t,e):this.isQuanX()?$prefs.setValueForKey(t,e):this.isNode()?(this.data=this.loaddata(),this.data[e]=t,this.writedata(),!0):this.data&&this.data[e]||null}initGotEnv(t){this.got=this.got?this.got:require("got"),this.cktough=this.cktough?this.cktough:require("tough-cookie"),this.ckjar=this.ckjar?this.ckjar:new this.cktough.CookieJar,t&&(t.headers=t.headers?t.headers:{},void 0===t.headers.Cookie&&void 0===t.cookieJar&&(t.cookieJar=this.ckjar))}get(t,e=(()=>{})){t.headers&&(delete t.headers["Content-Type"],delete t.headers["Content-Length"]),this.isSurge()||this.isLoon()?(this.isSurge()&&this.isNeedRewrite&&(t.headers=t.headers||{},Object.assign(t.headers,{"X-Surge-Skip-Scripting":!1})),$httpClient.get(t,(t,s,i)=>{!t&&s&&(s.body=i,s.statusCode=s.status),e(t,s,i)})):this.isQuanX()?(this.isNeedRewrite&&(t.opts=t.opts||{},Object.assign(t.opts,{hints:!1})),$task.fetch(t).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>e(t))):this.isNode()&&(this.initGotEnv(t),this.got(t).on("redirect",(t,e)=>{try{if(t.headers["set-cookie"]){const s=t.headers["set-cookie"].map(this.cktough.Cookie.parse).toString();this.ckjar.setCookieSync(s,null),e.cookieJar=this.ckjar}}catch(t){this.logErr(t)}}).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>{const{message:s,response:i}=t;e(s,i,i&&i.body)}))}post(t,e=(()=>{})){if(t.body&&t.headers&&!t.headers["Content-Type"]&&(t.headers["Content-Type"]="application/x-www-form-urlencoded"),t.headers&&delete t.headers["Content-Length"],this.isSurge()||this.isLoon())this.isSurge()&&this.isNeedRewrite&&(t.headers=t.headers||{},Object.assign(t.headers,{"X-Surge-Skip-Scripting":!1})),$httpClient.post(t,(t,s,i)=>{!t&&s&&(s.body=i,s.statusCode=s.status),e(t,s,i)});else if(this.isQuanX())t.method="POST",this.isNeedRewrite&&(t.opts=t.opts||{},Object.assign(t.opts,{hints:!1})),$task.fetch(t).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>e(t));else if(this.isNode()){this.initGotEnv(t);const{url:s,...i}=t;this.got.post(s,i).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>{const{message:s,response:i}=t;e(s,i,i&&i.body)})}}time(t){let e={"M+":(new Date).getMonth()+1,"d+":(new Date).getDate(),"H+":(new Date).getHours(),"m+":(new Date).getMinutes(),"s+":(new Date).getSeconds(),"q+":Math.floor(((new Date).getMonth()+3)/3),S:(new Date).getMilliseconds()};/(y+)/.test(t)&&(t=t.replace(RegExp.$1,((new Date).getFullYear()+"").substr(4-RegExp.$1.length)));for(let s in e)new RegExp("("+s+")").test(t)&&(t=t.replace(RegExp.$1,1==RegExp.$1.length?e[s]:("00"+e[s]).substr((""+e[s]).length)));return t}msg(e=t,s="",i="",r){const o=t=>{if(!t)return t;if("string"==typeof t)return this.isLoon()?t:this.isQuanX()?{"open-url":t}:this.isSurge()?{url:t}:void 0;if("object"==typeof t){if(this.isLoon()){let e=t.openUrl||t.url||t["open-url"],s=t.mediaUrl||t["media-url"];return{openUrl:e,mediaUrl:s}}if(this.isQuanX()){let e=t["open-url"]||t.url||t.openUrl,s=t["media-url"]||t.mediaUrl;return{"open-url":e,"media-url":s}}if(this.isSurge()){let e=t.url||t.openUrl||t["open-url"];return{url:e}}}};this.isMute||(this.isSurge()||this.isLoon()?$notification.post(e,s,i,o(r)):this.isQuanX()&&$notify(e,s,i,o(r)));let h=["","==============\ud83d\udce3\u7cfb\u7edf\u901a\u77e5\ud83d\udce3=============="];h.push(e),s&&h.push(s),i&&h.push(i),console.log(h.join("\n")),this.logs=this.logs.concat(h)}log(...t){t.length>0&&(this.logs=[...this.logs,...t]),console.log(t.join(this.logSeparator))}logErr(t,e){const s=!this.isSurge()&&!this.isQuanX()&&!this.isLoon();s?this.log("",`\u2757\ufe0f${this.name}, \u9519\u8bef!`,t.stack):this.log("",`\u2757\ufe0f${this.name}, \u9519\u8bef!`,t)}wait(t){return new Promise(e=>setTimeout(e,t))}done(t={}){const e=(new Date).getTime(),s=(e-this.startTime)/1e3;this.log("",`\ud83d\udd14${this.name}, \u7ed3\u675f! \ud83d\udd5b ${s} \u79d2`),this.log(),(this.isSurge()||this.isQuanX()||this.isLoon())&&$done(t)}}(t,e)} \ No newline at end of file + +function nebulaHost(api,body){ + return { + url: 'https://nebula.kuaishou.com/rest/n/nebula/'+api, + headers:{ + 'Host': 'nebula.kuaishou.com', + 'Cookie': cookieVal, + 'Content-Type': 'application/json;charset=utf-8', + 'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1.2 Mobile/15E148 Safari/604.1' + }, + body: body + } +} + +function GetCookie() { + var UA = $request.headers['User-Agent'] + if ($request && $request.method != `OPTIONS` && UA.indexOf('ksNebula') > -1) { + const cookieVal = $request.headers['Cookie'] + if (cookieVal) $.setdata(cookieVal, 'cookie_ks'); + $.log(`${$.name}获取Cookie: 成功, cookieVal: $ {cookieVal}`); + $.msg($.name, `获取极速Cookie: 成功🎉`, ``) + } else if ($request && $request.method != `OPTIONS` && UA.indexOf("ksNebula") == -1) { + const cookie = $request.headers['Cookie'] ; + cookieVal = cookie.match(/appver=[0-9\.]+/)+cookie.match(/; client_key=\w+/)+cookie.match(/; token=[0-9a-z-]+/)+cookie.match(/; userId=\d+/); + uid= cookieVal.match(/userId=\d+/); + if (ks_tokens) { + if (ks_tokens.indexOf(uid) > -1) { + $.log("cookie重复,已跳过") + } else if (ks_tokens.indexOf(uid) == -1) { + Cookies = ks_tokens + "&" + cookieVal; + $.setdata(Cookies, 'cookie_ks'); + ck = Cookies.split("&"); + $.msg($.name, "获取正式版Cookie" + ck.length + ": 成功🎉", ``) + } + } else { + $.setdata(cookieVal, 'cookie_ks'); + $.msg($.name, `获取正式版Cookie: 成功🎉`, ``) + } + } +} + +function bdinvet(){ + const bdurl = { + url: 'http://apissl.gifshow.com/rest/nebula/inviteCode/bind?c=a&apptype=2&did=D4B25234-725E-4D81-92B1-74DB50DA409E&kpn=NEBULA&keyconfig_state=1&deviceBit=0&sw=1242&kpf=IPHONE&sourceType=9&sys=ios13.7&sh=2208&kcv=1312&browseType=3&net=%E4%B8%AD%E5%9B%BD%E7%94%B5%E4%BF%A1_5&darkMode=false&inviteCode=774010415&ver=9.0&sync=1&isp=CTCC&mod=iPhone8%2C2&ud=953324934&cold_launch_time_ms=1613871841353&vague=0&egid=DFP942522CAECD367BB4299B87A4D670C60F89C2D9ED85DE0DEEC1E63A2925D1&appver=9.0.50.594', + headers: nebulaHost().headers, + body: cookieVal + }; + $.post(bdurl, (error, resp, data) => { + // $.log(resp.statusCode) + }) +} +function Env(t,e){class s{constructor(t){this.env=t}send(t,e="GET"){t="string"==typeof t?{url:t}:t;let s=this.get;return"POST"===e&&(s=this.post),new Promise((e,i)=>{s.call(this,t,(t,s,r)=>{t?i(t):e(s)})})}get(t){return this.send.call(this.env,t)}post(t){return this.send.call(this.env,t,"POST")}}return new class{constructor(t,e){this.name=t,this.http=new s(this),this.data=null,this.dataFile="box.dat",this.logs=[],this.isMute=!1,this.isNeedRewrite=!1,this.logSeparator="\n",this.startTime=(new Date).getTime(),Object.assign(this,e),this.log("",`\ud83d\udd14${this.name}, \u5f00\u59cb!`)}isNode(){return"undefined"!=typeof module&&!!module.exports}isQuanX(){return"undefined"!=typeof $task}isSurge(){return"undefined"!=typeof $httpClient&&"undefined"==typeof $loon}isLoon(){return"undefined"!=typeof $loon}toObj(t,e=null){try{return JSON.parse(t)}catch{return e}}toStr(t,e=null){try{return JSON.stringify(t)}catch{return e}}getjson(t,e){let s=e;const i=this.getdata(t);if(i)try{s=JSON.parse(this.getdata(t))}catch{}return s}setjson(t,e){try{return this.setdata(JSON.stringify(t),e)}catch{return!1}}getScript(t){return new Promise(e=>{this.get({url:t},(t,s,i)=>e(i))})}runScript(t,e){return new Promise(s=>{let i=this.getdata("@chavy_boxjs_userCfgs.httpapi");i=i?i.replace(/\n/g,"").trim():i;let r=this.getdata("@chavy_boxjs_userCfgs.httpapi_timeout");r=r?1*r:20,r=e&&e.timeout?e.timeout:r;const[o,h]=i.split("@"),a={url:`http://${h}/v1/scripting/evaluate`,body:{script_text:t,mock_type:"cron",timeout:r},headers:{"X-Key":o,Accept:"*/*"}};this.post(a,(t,e,i)=>s(i))}).catch(t=>this.logErr(t))}loaddata(){if(!this.isNode())return{};{this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(this.dataFile),e=this.path.resolve(process.cwd(),this.dataFile),s=this.fs.existsSync(t),i=!s&&this.fs.existsSync(e);if(!s&&!i)return{};{const i=s?t:e;try{return JSON.parse(this.fs.readFileSync(i))}catch(t){return{}}}}}writedata(){if(this.isNode()){this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(this.dataFile),e=this.path.resolve(process.cwd(),this.dataFile),s=this.fs.existsSync(t),i=!s&&this.fs.existsSync(e),r=JSON.stringify(this.data);s?this.fs.writeFileSync(t,r):i?this.fs.writeFileSync(e,r):this.fs.writeFileSync(t,r)}}lodash_get(t,e,s){const i=e.replace(/\[(\d+)\]/g,".$1").split(".");let r=t;for(const t of i)if(r=Object(r)[t],void 0===r)return s;return r}lodash_set(t,e,s){return Object(t)!==t?t:(Array.isArray(e)||(e=e.toString().match(/[^.[\]]+/g)||[]),e.slice(0,-1).reduce((t,s,i)=>Object(t[s])===t[s]?t[s]:t[s]=Math.abs(e[i+1])>>0==+e[i+1]?[]:{},t)[e[e.length-1]]=s,t)}getdata(t){let e=this.getval(t);if(/^@/.test(t)){const[,s,i]=/^@(.*?)\.(.*?)$/.exec(t),r=s?this.getval(s):"";if(r)try{const t=JSON.parse(r);e=t?this.lodash_get(t,i,""):e}catch(t){e=""}}return e}setdata(t,e){let s=!1;if(/^@/.test(e)){const[,i,r]=/^@(.*?)\.(.*?)$/.exec(e),o=this.getval(i),h=i?"null"===o?null:o||"{}":"{}";try{const e=JSON.parse(h);this.lodash_set(e,r,t),s=this.setval(JSON.stringify(e),i)}catch(e){const o={};this.lodash_set(o,r,t),s=this.setval(JSON.stringify(o),i)}}else s=this.setval(t,e);return s}getval(t){return this.isSurge()||this.isLoon()?$persistentStore.read(t):this.isQuanX()?$prefs.valueForKey(t):this.isNode()?(this.data=this.loaddata(),this.data[t]):this.data&&this.data[t]||null}setval(t,e){return this.isSurge()||this.isLoon()?$persistentStore.write(t,e):this.isQuanX()?$prefs.setValueForKey(t,e):this.isNode()?(this.data=this.loaddata(),this.data[e]=t,this.writedata(),!0):this.data&&this.data[e]||null}initGotEnv(t){this.got=this.got?this.got:require("got"),this.cktough=this.cktough?this.cktough:require("tough-cookie"),this.ckjar=this.ckjar?this.ckjar:new this.cktough.CookieJar,t&&(t.headers=t.headers?t.headers:{},void 0===t.headers.Cookie&&void 0===t.cookieJar&&(t.cookieJar=this.ckjar))}get(t,e=(()=>{})){t.headers&&(delete t.headers["Content-Type"],delete t.headers["Content-Length"]),this.isSurge()||this.isLoon()?(this.isSurge()&&this.isNeedRewrite&&(t.headers=t.headers||{},Object.assign(t.headers,{"X-Surge-Skip-Scripting":!1})),$httpClient.get(t,(t,s,i)=>{!t&&s&&(s.body=i,s.statusCode=s.status),e(t,s,i)})):this.isQuanX()?(this.isNeedRewrite&&(t.opts=t.opts||{},Object.assign(t.opts,{hints:!1})),$task.fetch(t).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>e(t))):this.isNode()&&(this.initGotEnv(t),this.got(t).on("redirect",(t,e)=>{try{if(t.headers["set-cookie"]){const s=t.headers["set-cookie"].map(this.cktough.Cookie.parse).toString();this.ckjar.setCookieSync(s,null),e.cookieJar=this.ckjar}}catch(t){this.logErr(t)}}).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>{const{message:s,response:i}=t;e(s,i,i&&i.body)}))}post(t,e=(()=>{})){if(t.body&&t.headers&&!t.headers["Content-Type"]&&(t.headers["Content-Type"]="application/x-www-form-urlencoded"),t.headers&&delete t.headers["Content-Length"],this.isSurge()||this.isLoon())this.isSurge()&&this.isNeedRewrite&&(t.headers=t.headers||{},Object.assign(t.headers,{"X-Surge-Skip-Scripting":!1})),$httpClient.post(t,(t,s,i)=>{!t&&s&&(s.body=i,s.statusCode=s.status),e(t,s,i)});else if(this.isQuanX())t.method="POST",this.isNeedRewrite&&(t.opts=t.opts||{},Object.assign(t.opts,{hints:!1})),$task.fetch(t).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>e(t));else if(this.isNode()){this.initGotEnv(t);const{url:s,...i}=t;this.got.post(s,i).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>{const{message:s,response:i}=t;e(s,i,i&&i.body)})}}time(t){let e={"M+":(new Date).getMonth()+1,"d+":(new Date).getDate(),"H+":(new Date).getHours(),"m+":(new Date).getMinutes(),"s+":(new Date).getSeconds(),"q+":Math.floor(((new Date).getMonth()+3)/3),S:(new Date).getMilliseconds()};/(y+)/.test(t)&&(t=t.replace(RegExp.$1,((new Date).getFullYear()+"").substr(4-RegExp.$1.length)));for(let s in e)new RegExp("("+s+")").test(t)&&(t=t.replace(RegExp.$1,1==RegExp.$1.length?e[s]:("00"+e[s]).substr((""+e[s]).length)));return t}msg(e=t,s="",i="",r){const o=t=>{if(!t)return t;if("string"==typeof t)return this.isLoon()?t:this.isQuanX()?{"open-url":t}:this.isSurge()?{url:t}:void 0;if("object"==typeof t){if(this.isLoon()){let e=t.openUrl||t.url||t["open-url"],s=t.mediaUrl||t["media-url"];return{openUrl:e,mediaUrl:s}}if(this.isQuanX()){let e=t["open-url"]||t.url||t.openUrl,s=t["media-url"]||t.mediaUrl;return{"open-url":e,"media-url":s}}if(this.isSurge()){let e=t.url||t.openUrl||t["open-url"];return{url:e}}}};this.isMute||(this.isSurge()||this.isLoon()?$notification.post(e,s,i,o(r)):this.isQuanX()&&$notify(e,s,i,o(r)));let h=["","==============\ud83d\udce3\u7cfb\u7edf\u901a\u77e5\ud83d\udce3=============="];h.push(e),s&&h.push(s),i&&h.push(i),console.log(h.join("\n")),this.logs=this.logs.concat(h)}log(...t){t.length>0&&(this.logs=[...this.logs,...t]),console.log(t.join(this.logSeparator))}logErr(t,e){const s=!this.isSurge()&&!this.isQuanX()&&!this.isLoon();s?this.log("",`\u2757\ufe0f${this.name}, \u9519\u8bef!`,t.stack):this.log("",`\u2757\ufe0f${this.name}, \u9519\u8bef!`,t)}wait(t){return new Promise(e=>setTimeout(e,t))}done(t={}){const e=(new Date).getTime(),s=(e-this.startTime)/1e3;this.log("",`\ud83d\udd14${this.name}, \u7ed3\u675f! \ud83d\udd5b ${s} \u79d2`),this.log(),(this.isSurge()||this.isQuanX()||this.isLoon())&&$done(t)}}(t,e)} diff --git a/Task/midu_Read.js b/Task/midu_Read.js index 84f63cdccd..96c05ead38 100644 --- a/Task/midu_Read.js +++ b/Task/midu_Read.js @@ -1,11 +1,18 @@ - +/* +MIDU_TOKEN 为 "https://apiwz.midukanshu.com/user/readTimeBase/readTime"此链接完整请求头; +MIDU_TIME 为 "https://apiwz.midukanshu.com/user/readTimeBase/readTime"此链接请求体,格式为 "dataEncStr=XXX; +MIDU_SIGN 为 "https://apiwz.midukanshu.com/wz/task/" 完整请求体,格式为 "fullVersion=XXX" +以上全部值不许换行,多账号用#分隔; +多账号退出一账号可能某些任务会提示失效 +由于运行时间较长,则只在Actions运行 +*/ const cookieName = '米读阅读时长' const $ = new Env(cookieName) let tokenArr = [], TimeArr = [],SignArr= []; - + const bind = true; if ($.isNode()) { if (process.env.MIDU_TOKEN && process.env.MIDU_TOKEN.indexOf('#') > -1) { - miduToken = process.env.MIDU_TOKEN.split('#'); + miduToken = process.env.MIDU_TOKEN.split('#'); } else { miduToken = process.env.MIDU_TOKEN.split() }; @@ -23,17 +30,17 @@ if ($.isNode()) { if (miduToken[item]) { tokenArr.push(miduToken[item]) } - }) + }); Object.keys(ReadBodys).forEach((item) => { if (ReadBodys[item]) { TimeArr.push(ReadBodys[item]) } - }) + }); Object.keys(SignBodys).forEach((item) => { if (SignBodys[item]) { SignArr.push(SignBodys[item]) } - }) + }); } else { tokenArr.push($.getdata('tokenMidu_read')); TimeArr.push($.getdata('senku_readTimebody_midu')); @@ -47,31 +54,46 @@ if ($.isNode()) { return; } if ($.isNode()){ - console.log(`\n============ 脚本执行来自 Github Action ==============\n`) console.log(`============ 脚本执行-国际标准时间(UTC):${new Date().toLocaleString()} =============\n`) - console.log(`============ 脚本执行-北京时间(UTC+8):${new Date(new Date().getTime() + 8 * 60 * 60 * 1000).toLocaleString()}=============\n`) + console.log(`============ 脚本执行-北京时间(UTC+8):${new Date(new Date().getTime() + 8 * 60 * 60 * 1000).toLocaleString()} =============\n`) + console.log(`============ 共${tokenArr.length}个米读账号 =============\n`) }; + for (let i = 0; i < tokenArr.length; i++) { if (tokenArr[i]) { - tokenVal = tokenArr[i]; + headerVal = tokenArr[i]; bodyVal = TimeArr[i]; drawVal = SignArr[i]; - //console.log(bodyVal) $.index = i + 1; + //console.log(tokenArr) console.log(`-------------------------\n\n开始【米读账号${$.index}】`) - $.log(`🔔 ${cookieName}`) - await readTime(); - await drawPrize(); - await prizeTask(); - await prizeInfo(); - await dice_roll(); - await dice_double(); - await signDay(); - await signVideo() - } - } + tkVal = drawVal.match(/tk=(\w+)/)[1] + await userInfo(); + for (j=0;j<10;j++){ + await readTime() + }; + await prizeInfo(); + if (prizeinfo && prizeinfo.data && prizeinfo.data.total_num) { + await prizeTask(), + await drawPrize() + }; + await addDraw(); + await taskTime(); + await OthersAd(); + await dice_addnum(); + await dice_roll(); + await dice_double(); + if (bind) { + await Bind(); + } + await signDay(); + await signVideo() + } + } })() - .catch((e) => $.log(`❌ ${cookieName} 签到失败: ${e}`)) + .catch((e) => $.logErr(e)) + .finally(() => $.done()) + // 阅读时长 @@ -79,13 +101,12 @@ function readTime() { return new Promise((resolve, reject) => { let request = { url: "https://apiwz.midukanshu.com/user/readTimeBase/readTime", - headers: {'token' : tokenVal,'User-Agent' : `MRSpeedNovel/0918.1649 CFNetwork/1128.0.1 Darwin/19.6.0`,'mobile-brand': 'iPhone','Content-Type': 'application/x-www-form-urlencoded' - }, - body: bodyVal, + headers: JSON.parse(headerVal), + body: bodyVal } - $.post(request, (error, response, data) => { + $.post(request, async(error, response, data) => { try { - $.log(`❕ ${cookieName} readTime - response: ${JSON.stringify(response)}`) + //$.log(`❕ ${cookieName} readTime - response: ${JSON.stringify(data)}\n`) readtime = JSON.parse(data) let subTitle = '' let detail = '' @@ -94,85 +115,178 @@ function readTime() { const readTotalMinute = readtime.data.readTotalMinute const total_coin = readtime.data.total_coin coin == 0 ? detail += `` : detail += `【阅读时长】获得${coin}💰` - if (readTotalMinute % 20 == 0) { - readTotalMinute ? detail += ` 阅读时长${readTotalMinute / 2}分钟,该账户:${total_coin}💰` : detail += `该账户:${total_coin}💰` - $.msg(cookieName, subTitle, detail) - } else if ($.getdata('debug') == 'true') { + console.log("总计阅读时长"+readTotalMinute / 2+"分钟,本次获得+"+`${coin}金币,请等待30s后执行下一次阅读\n`) readTotalMinute ? detail += ` 阅读时长${readTotalMinute / 2}分钟,该账户:${total_coin}💰` : detail += `该账户:${total_coin}💰` - $.msg(cookieName, subTitle, detail) + await $.wait(30000); + + //$.msg(cookieName, subTitle, detail) - - } } else if (readTime.code != 0) { detail += `【阅读时长】错误代码${readtime.code},错误信息${readtime.message}` $.msg(cookieName, subTitle, detail) - } else { - detail += '【阅读时长】失败' - $.msg(cookieName, subTitle, detail) - } - resolve() + } + } catch (e) { $.msg(cookieName, `阅读时长: 失败`, `说明: ${e}`) $.log(`❌ ${cookieName} readTime - 签到失败: ${e}`) - $.log(`❌ ${cookieName} readTime - response: ${JSON.stringify(response)}`) + $.log(`❌ ${cookieName} readTime - response: ${JSON.stringify(data)}\n`) + } + resolve() + }) + }) +} + +function drawPrize() { + return new Promise((resolve, reject) => { + const url = { + url: 'https://apiwz.midukanshu.com/wz/task/drawPrize?' + drawVal, + headers: JSON.parse(headerVal), + } + $.post(url, (error, response, data) => { + try { + $.log(`🐍🐢 ${cookieName} drawPrize - response: ${JSON.stringify(data)}\n`) + drawprize = JSON.parse(data) + if(drawprize.code==0){ + console.log("转盘抽奖任务:"+drawprize.data.title) + } + + } catch (e) { + // $.msg(cookieName, `抽奖: 失败`, `说明: ${e}`) + $.log(`❌ ${cookieName} drawPrize - 抽奖失败: ${e}`) + $.log(`❌ ${cookieName} drawPrize - response: ${JSON.stringify(data)}\n`) + + } + resolve() + }) + }) +} +// 用户信息 +function userInfo() { + return new Promise((resolve, reject) => { + const url = { + url: 'https://apiwz.midukanshu.com/wz/user/getInfo', + headers: JSON.parse(headerVal), + body: bodyVal + } + $.post(url, (error, response, data) => { + try { + //$.log(`🐍🐢 ${cookieName} userInfo - response: ${JSON.stringify(data)}`) + userinfo = JSON.parse(data) + if (userinfo.code==0){ + nick = userinfo.data.nickname + total_coin = userinfo.data.goldCoin + corner = userinfo.data.goldCoinMoney + invite_code = userinfo.data.invite_code + today_coin = userinfo.data.todayGoldCoin + console.log("总计金币:"+total_coin+" 现金收益"+corner+'\n您今日所得总金币为'+ today_coin+' 您的邀请码为'+ invite_code+'\n') + } + resolve() + } catch (e) { + $.msg(cookieName, `获取用户信息: 失败`, `说明: ${e}`) + $.log(`❌ ${cookieName} userInfo - 获取用户信息失败: ${e}`) + $.log(`❌ ${cookieName} userInfo - data: ${JSON.stringify(data)}`) resolve() } }) }) } -function drawPrize() { + +function Bind() { return new Promise((resolve, reject) => { - const drawPrizeurlVal = 'https://apiwz.midukanshu.com/wz/task/drawPrize' const url = { - url: drawPrizeurlVal, + url: 'http://fisson.1sapp.com/nlx/shareLink/tmpBind', + headers: JSON.parse(headerVal), + body: 'app_id=7&act_type=1&act_name=grad_pupil&invite_code=A1051999596&telephone=' + userinfo.data.mobile + } + url.headers['Host'] = 'fisson.1sapp.com' + $.post(url, (error, response, data) => { + resolve() + }) + }) +} + + +// 额外奖励 +function addDraw() { + return new Promise((resolve, reject) => { + url = { + url: 'https://apiwz.midukanshu.com/wz/task/weekReward', headers: {}, - body: drawVal + body: drawVal+"&draw_num=28&sign=36646430333630313c3c353c6661326136333266326036353663333232363d3d" } - url.headers['token'] = tokenVal url.headers['Host'] = 'apiwz.midukanshu.com' url.headers['Content-Type'] = 'application/x-www-form-urlencoded' - url.headers['User-Agent'] = 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 qapp miduapp' + url.headers['User-Agent'] = 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 qapp miduapp' $.post(url, (error, response, data) => { try { - $.log(`🐍🐢 ${cookieName} drawPrize - response: ${JSON.stringify(response)}`) - if (data) { - drawprize = JSON.parse(data) - } + // $.log(`🐍🐢 ${cookieName} addDraw - response: ${JSON.stringify(data)}\n`) + add_Draw = JSON.parse(data) + if(add_Draw.code==0){ + console.log("转盘额外奖励:"+add_Draw.data.msg) + } resolve() } catch (e) { - // $.msg(cookieName, `抽奖: 失败`, `说明: ${e}`) - $.log(`❌ ${cookieName} drawPrize - 抽奖失败: ${e}`) - $.log(`❌ ${cookieName} drawPrize - response: ${JSON.stringify(response)}`) + // $.msg(cookieName, `额外奖励: 失败`, `说明: ${e}`) + $.log(`❌ ${cookieName} addDraw - 转盘额外奖励失败: ${e}`) + $.log(`❌ ${cookieName} addDraw - response: ${JSON.stringify(data)}\n`) resolve() } }) }) } +function taskTime() { + return new Promise((resolve, reject) => { + const url = { + url: 'https://apiwz.midukanshu.com/wz/task/time' , + headers: {}, + body: drawVal + } + url.headers['Host'] = 'apiwz.midukanshu.com' + url.headers['Content-Type'] = 'application/x-www-form-urlencoded' + url.headers['User-Agent'] = 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 qapp miduapp' + $.post(url, (error, response, data) => { + try { + // $.log(`🐍🐢 ${cookieName} taskTime - response: ${JSON.stringify(data)}\n`) + _taskTime = JSON.parse(data) + if(_taskTime.code==0){ + console.log("定时任务:"+"+"+_taskTime.data.amount) + } + resolve() + } catch (e) { + $.log(`❌ ${cookieName} taskTime - 定时任务失败: ${e}`) + $.log(`❌ ${cookieName} taskTime - response: ${JSON.stringify(data)}\n`) + resolve() + } + }) + }) +} + + // 观看视频获取抽奖机会 function prizeTask() { return new Promise((resolve, reject) => { - const prizeTaskurlVal = 'https://apiwz.midukanshu.com/wz/task/prizeTask' + const prizeTaskurlVal = 'https://apiwz.midukanshu.com/wz/task/prizeTask?'+drawVal const url = { url: prizeTaskurlVal, headers: {}, - body: drawVal } - url.headers['token'] = tokenVal + //url.headers['token'] = tokenVal url.headers['Host'] = 'apiwz.midukanshu.com' url.headers['Content-Type'] = 'application/x-www-form-urlencoded' - url.headers['User-Agent'] = 'Mozilla/5.0 (iPhone; CPU iPhone OS 12_4_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148' + url.headers['User-Agent'] = 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 qapp miduapp' $.post(url, (error, response, data) => { try { - $.log(`🐍🐢 ${cookieName} prizeTask - response: ${JSON.stringify(response)}`) - if (data) { - prizetask = JSON.parse(data) - } + // $.log(`🐍🐢 ${cookieName} prizeTask - response: ${JSON.stringify(data)}\n`) + prizetask = JSON.parse(data) + if(prizetask.code==0){ + console.log("抽奖次数: "+prizetask.data.title) + } resolve() } catch (e) { // $.msg(cookieName, `观看视频抽奖: 失败`, `说明: ${e}`) $.log(`❌ ${cookieName} prizeTask - 观看视频抽奖失败: ${e}`) - $.log(`❌ ${cookieName} prizeTask - response: ${JSON.stringify(response)}`) + $.log(`❌ ${cookieName} prizeTask - response: ${JSON.stringify(data)}\n`) resolve() } }) @@ -182,27 +296,26 @@ function prizeTask() { // 抽奖信息 function prizeInfo() { return new Promise((resolve, reject) => { - const prizeInfourlVal = 'https://apiwz.midukanshu.com/wz/task/prizeList' const url = { - url: prizeInfourlVal, + url: 'https://apiwz.midukanshu.com/wz/task/prizeList', headers: {}, body: drawVal } - url.headers['token'] = tokenVal url.headers['Host'] = 'apiwz.midukanshu.com' url.headers['Content-Type'] = 'application/x-www-form-urlencoded' - url.headers['User-Agent'] = 'Mozilla/5.0 (iPhone; CPU iPhone OS 12_4_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148' + url.headers['User-Agent'] = 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 qapp miduapp' $.post(url, (error, response, data) => { try { - // $.log(`🐍🐢 ${cookieName} prizeInfo - response: ${JSON.stringify(response)}`) + //$.log(`🐍🐢 ${cookieName} prizeInfo - response: ${JSON.stringify(data)}\n`) if (data) { prizeinfo = JSON.parse(data) + console.log("今日抽奖信息:"+prizeinfo.data.btnText) } resolve() } catch (e) { // $.msg(cookieName, `抽奖信息: 失败`, `说明: ${e}`) $.log(`❌ ${cookieName} prizeInfo - 抽奖信息失败: ${e}`) - $.log(`❌ ${cookieName} prizeInfo - response: ${JSON.stringify(response)}`) + $.log(`❌ ${cookieName} prizeInfo - response: ${JSON.stringify(data)}\n`) resolve() } }) @@ -212,26 +325,28 @@ function prizeInfo() { // 掷骰子 function dice_roll() { return new Promise((resolve, reject) => { - const dice_roll_urlVal = 'https://apiwz.midukanshu.com/wz/dice/roll' const url = { - url: dice_roll_urlVal, + url: 'https://apiwz.midukanshu.com/wz/dice/roll', headers: {}, body: drawVal } url.headers['Host'] = 'apiwz.midukanshu.com' url.headers['Content-Type'] = 'application/x-www-form-urlencoded' - url.headers['User-Agent'] = 'Mozilla/5.0 (iPhone; CPU iPhone OS 12_4_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148' + url.headers['User-Agent'] = 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148' $.post(url, (error, response, data) => { try { - $.log(`🐍🐢 ${cookieName} dice_roll - response: ${JSON.stringify(response)}`) - if (JSON.parse(data).code == 0) { - rollList=JSON.parse(data) + // $.log(`🐍🐢 ${cookieName} dice_roll - response: ${JSON.stringify(data)}\n`) + rollList=JSON.parse(data) + if (rollList.code == 0) { + console.log("掷骰子获得"+rollList.data.roll_coin+"金币") + } else if (rollList.code == '-10203'){ + console.log("掷骰子任务:"+rollList.message) } resolve() } catch (e) { $.msg(cookieName, `掷骰子: 失败`, `说明: ${e}`) $.log(`❌ ${cookieName} dice_roll - 掷骰子失败: ${e}`) - $.log(`❌ ${cookieName} dice_roll - response: ${JSON.stringify(response)}`) + $.log(`❌ ${cookieName} dice_roll - response: ${JSON.stringify(data)}\n`) resolve() } }) @@ -241,55 +356,87 @@ function dice_roll() { // 骰子双倍奖励 function dice_double() { return new Promise((resolve, reject) => { - const dice_double_urlVal = 'https://apiwz.midukanshu.com/wz/dice/doubleReward' const url = { - url: dice_double_urlVal, + url: 'https://apiwz.midukanshu.com/wz/dice/doubleReward', headers: {}, body: drawVal } url.headers['Host'] = 'apiwz.midukanshu.com' url.headers['Content-Type'] = 'application/x-www-form-urlencoded' - url.headers['User-Agent'] = 'Mozilla/5.0 (iPhone; CPU iPhone OS 12_4_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148' - url.headers['token'] = tokenVal + url.headers['User-Agent'] = 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 qapp miduapp' + //url.headers['token'] = tokenVal $.post(url, (error, response, data) => { try { - $.log(`🐍🐢 ${cookieName} dice_double - response: ${JSON.stringify(response)}`) - if (JSON.parse(data).code == 0) { - doubleList=JSON.parse(data) + $.log(`🐍🐢 ${cookieName} dice_double - response: ${JSON.stringify(data)}\n`) + doubleList=JSON.parse(data) + if (doubleList.code == 0) { + console.log("骰子双倍奖励:"+doubleList.message) + } else if (doubleList.code == '-10205'){ + console.log("骰子双倍奖励:"+doubleList.message) } resolve() } catch (e) { $.msg(cookieName, `骰子双倍奖励: 失败`, `说明: ${e}`) $.log(`❌ ${cookieName} dice_double - 骰子双倍奖励失败: ${e}`) - $.log(`❌ ${cookieName} dice_double - response: ${JSON.stringify(response)}`) + $.log(`❌ ${cookieName} dice_double - response: ${JSON.stringify(data)}\n`) + resolve() + } + }) + }) +} +//获取骰子次数: +function dice_addnum() { + return new Promise((resolve, reject) => { + const dice_addnum_urlVal = 'https://apiwz.midukanshu.com/wz/dice/addChangeNumByRewardVideo?' + drawVal + const url = { + url: dice_addnum_urlVal, + headers: {} + } + url.headers['Host'] = 'apiwz.midukanshu.com' + url.headers['Content-Type'] = 'application/x-www-form-urlencoded' + url.headers['User-Agent'] = 'User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 14_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 miduapp qapp' + $.post(url, (error, response, data) => { + try { + // $.log(`🐍🐢 ${cookieName} dice_addnum - response: ${JSON.stringify(data)}`) + diceaddnum=JSON.parse(data) + if(diceaddnum.code=='-10208'){ + console.log("获取骰子次数:"+diceaddnum.message) + } + resolve() + } catch (e) { + $.msg(cookieName, `获取骰子次数: 失败`, `说明: ${e}`) + $.log(`❌ ${cookieName} dice_addnum - 获取骰子次数失败: ${e}`) + $.log(`❌ ${cookieName} dice_addnum - response: ${JSON.stringify(data)}`) resolve() } }) }) } + // 每日签到 function signDay() { return new Promise((resolve, reject) => { - const signurlVal = 'https://apiwz.midukanshu.com/wz/task/signInV2' const url = { - url: signurlVal, + url: "https://apiwz.midukanshu.com/wz/task/signInV2?"+ drawVal, headers: {}, - body: drawVal } - url.headers['token'] = tokenVal + //url.headers['token'] = tokenVal url.headers['Host'] = 'apiwz.midukanshu.com' url.headers['Content-Type'] = 'application/x-www-form-urlencoded' - url.headers['User-Agent'] = 'Mozilla/5.0 (iPhone; CPU iPhone OS 12_4_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148' + url.headers['User-Agent'] = 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 qapp miduapp' $.post(url, (error, response, data) => { try { - $.log(`🐍🐢 ${cookieName} signDay - response: ${JSON.stringify(response)}`) + //$.log(`🐍🐢 ${cookieName} signDay - response: ${JSON.stringify(data)}\n`) _signDay = JSON.parse(data) + if(_signDay.code==0){ + console.log("每日签到:"+_signDay.data.amount+"金币") + } resolve() } catch (e) { $.msg(cookieName, `签到结果: 失败`, `说明: ${e}`) $.log(`❌ ${cookieName} signDay - 签到失败: ${e}`) - $.log(`❌ ${cookieName} signDay - response: ${JSON.stringify(response)}`) + $.log(`❌ ${cookieName} signDay - response: ${JSON.stringify(data)}\n`) resolve() } }) @@ -298,26 +445,26 @@ function signDay() { // 签到视频奖励 function signVideo() { - return new Promise((resolve, reject) => { - const signVideourlVal = 'https://apiwz.midukanshu.com/wz/task/signVideoReward' + return new Promise((resolve, reject) => { const url = { - url: signVideourlVal, + url: 'https://apiwz.midukanshu.com/wz/task/signVideoReward', headers: {}, body: drawVal } - url.headers['Host'] = 'apiwz.midukanshu.com' - url.headers['Content-Type'] = 'application/x-www-form-urlencoded' - url.headers['User-Agent'] = 'Mozilla/5.0 (iPhone; CPU iPhone OS 12_4_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148' - url.headers['token'] = tokenVal $.post(url, (error, response, data) => { try { - $.log(`🐍🐢 ${cookieName} signVideo - response: ${JSON.stringify(response)}`) + // $.log(`🐍🐢 ${cookieName} signVideo - response: ${JSON.stringify(data)}\n`) _signVideo = JSON.parse(data) + if (_signVideo.code == 0) { + console.log("签到视频奖励得"+_signVideo.data.amount+"金币") + } else { + console.log(_signVideo.message) + } resolve() } catch (e) { $.msg(cookieName, `签到视频: 失败`, `说明: ${e}`) $.log(`❌ ${cookieName} signVideo - 签到视频失败: ${e}`) - $.log(`❌ ${cookieName} signVideo - response: ${JSON.stringify(response)}`) + $.log(`❌ ${cookieName} signVideo - response: ${JSON.stringify(data)}\n`) resolve() } }) @@ -325,5 +472,31 @@ function signVideo() { } +function OthersAd() { + return new Promise((resolve, reject) => { + const otherVal = 'https://apiwz.midukanshu.com/activity/dividend/videoAdReward' + const url = { + url: otherVal, + headers: {}, + body: drawVal + } + $.post(url, (error, response, data) => { + try { + // $.log(`🐍🐢 ${cookieName} OthersAd - response: ${JSON.stringify(data)}\n`) + _OthersAd = JSON.parse(data) + if(_OthersAd.code==0){ + console.log("额外奖励: "+_OthersAd.data.msg) + } + resolve() + } catch (e) { + $.msg(cookieName, `额外奖励: 失败`, `说明: ${e}`) + $.log(`❌ ${cookieName} OthersAd - 额外奖励失败: ${e}`) + $.log(`❌ ${cookieName} OthersAd - response: ${JSON.stringify(data)}\n`) + resolve() + } + }) + }) +} + function Env(t,e){class s{constructor(t){this.env=t}send(t,e="GET"){t="string"==typeof t?{url:t}:t;let s=this.get;return"POST"===e&&(s=this.post),new Promise((e,i)=>{s.call(this,t,(t,s,r)=>{t?i(t):e(s)})})}get(t){return this.send.call(this.env,t)}post(t){return this.send.call(this.env,t,"POST")}}return new class{constructor(t,e){this.name=t,this.http=new s(this),this.data=null,this.dataFile="box.dat",this.logs=[],this.isMute=!1,this.isNeedRewrite=!1,this.logSeparator="\n",this.startTime=(new Date).getTime(),Object.assign(this,e),this.log("",`\ud83d\udd14${this.name}, \u5f00\u59cb!`)}isNode(){return"undefined"!=typeof module&&!!module.exports}isQuanX(){return"undefined"!=typeof $task}isSurge(){return"undefined"!=typeof $httpClient&&"undefined"==typeof $loon}isLoon(){return"undefined"!=typeof $loon}toObj(t,e=null){try{return JSON.parse(t)}catch{return e}}toStr(t,e=null){try{return JSON.stringify(t)}catch{return e}}getjson(t,e){let s=e;const i=this.getdata(t);if(i)try{s=JSON.parse(this.getdata(t))}catch{}return s}setjson(t,e){try{return this.setdata(JSON.stringify(t),e)}catch{return!1}}getScript(t){return new Promise(e=>{this.get({url:t},(t,s,i)=>e(i))})}runScript(t,e){return new Promise(s=>{let i=this.getdata("@chavy_boxjs_userCfgs.httpapi");i=i?i.replace(/\n/g,"").trim():i;let r=this.getdata("@chavy_boxjs_userCfgs.httpapi_timeout");r=r?1*r:20,r=e&&e.timeout?e.timeout:r;const[o,h]=i.split("@"),a={url:`http://${h}/v1/scripting/evaluate`,body:{script_text:t,mock_type:"cron",timeout:r},headers:{"X-Key":o,Accept:"*/*"}};this.post(a,(t,e,i)=>s(i))}).catch(t=>this.logErr(t))}loaddata(){if(!this.isNode())return{};{this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(this.dataFile),e=this.path.resolve(process.cwd(),this.dataFile),s=this.fs.existsSync(t),i=!s&&this.fs.existsSync(e);if(!s&&!i)return{};{const i=s?t:e;try{return JSON.parse(this.fs.readFileSync(i))}catch(t){return{}}}}}writedata(){if(this.isNode()){this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(this.dataFile),e=this.path.resolve(process.cwd(),this.dataFile),s=this.fs.existsSync(t),i=!s&&this.fs.existsSync(e),r=JSON.stringify(this.data);s?this.fs.writeFileSync(t,r):i?this.fs.writeFileSync(e,r):this.fs.writeFileSync(t,r)}}lodash_get(t,e,s){const i=e.replace(/\[(\d+)\]/g,".$1").split(".");let r=t;for(const t of i)if(r=Object(r)[t],void 0===r)return s;return r}lodash_set(t,e,s){return Object(t)!==t?t:(Array.isArray(e)||(e=e.toString().match(/[^.[\]]+/g)||[]),e.slice(0,-1).reduce((t,s,i)=>Object(t[s])===t[s]?t[s]:t[s]=Math.abs(e[i+1])>>0==+e[i+1]?[]:{},t)[e[e.length-1]]=s,t)}getdata(t){let e=this.getval(t);if(/^@/.test(t)){const[,s,i]=/^@(.*?)\.(.*?)$/.exec(t),r=s?this.getval(s):"";if(r)try{const t=JSON.parse(r);e=t?this.lodash_get(t,i,""):e}catch(t){e=""}}return e}setdata(t,e){let s=!1;if(/^@/.test(e)){const[,i,r]=/^@(.*?)\.(.*?)$/.exec(e),o=this.getval(i),h=i?"null"===o?null:o||"{}":"{}";try{const e=JSON.parse(h);this.lodash_set(e,r,t),s=this.setval(JSON.stringify(e),i)}catch(e){const o={};this.lodash_set(o,r,t),s=this.setval(JSON.stringify(o),i)}}else s=this.setval(t,e);return s}getval(t){return this.isSurge()||this.isLoon()?$persistentStore.read(t):this.isQuanX()?$prefs.valueForKey(t):this.isNode()?(this.data=this.loaddata(),this.data[t]):this.data&&this.data[t]||null}setval(t,e){return this.isSurge()||this.isLoon()?$persistentStore.write(t,e):this.isQuanX()?$prefs.setValueForKey(t,e):this.isNode()?(this.data=this.loaddata(),this.data[e]=t,this.writedata(),!0):this.data&&this.data[e]||null}initGotEnv(t){this.got=this.got?this.got:require("got"),this.cktough=this.cktough?this.cktough:require("tough-cookie"),this.ckjar=this.ckjar?this.ckjar:new this.cktough.CookieJar,t&&(t.headers=t.headers?t.headers:{},void 0===t.headers.Cookie&&void 0===t.cookieJar&&(t.cookieJar=this.ckjar))}get(t,e=(()=>{})){t.headers&&(delete t.headers["Content-Type"],delete t.headers["Content-Length"]),this.isSurge()||this.isLoon()?(this.isSurge()&&this.isNeedRewrite&&(t.headers=t.headers||{},Object.assign(t.headers,{"X-Surge-Skip-Scripting":!1})),$httpClient.get(t,(t,s,i)=>{!t&&s&&(s.body=i,s.statusCode=s.status),e(t,s,i)})):this.isQuanX()?(this.isNeedRewrite&&(t.opts=t.opts||{},Object.assign(t.opts,{hints:!1})),$task.fetch(t).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>e(t))):this.isNode()&&(this.initGotEnv(t),this.got(t).on("redirect",(t,e)=>{try{if(t.headers["set-cookie"]){const s=t.headers["set-cookie"].map(this.cktough.Cookie.parse).toString();this.ckjar.setCookieSync(s,null),e.cookieJar=this.ckjar}}catch(t){this.logErr(t)}}).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>{const{message:s,response:i}=t;e(s,i,i&&i.body)}))}post(t,e=(()=>{})){if(t.body&&t.headers&&!t.headers["Content-Type"]&&(t.headers["Content-Type"]="application/x-www-form-urlencoded"),t.headers&&delete t.headers["Content-Length"],this.isSurge()||this.isLoon())this.isSurge()&&this.isNeedRewrite&&(t.headers=t.headers||{},Object.assign(t.headers,{"X-Surge-Skip-Scripting":!1})),$httpClient.post(t,(t,s,i)=>{!t&&s&&(s.body=i,s.statusCode=s.status),e(t,s,i)});else if(this.isQuanX())t.method="POST",this.isNeedRewrite&&(t.opts=t.opts||{},Object.assign(t.opts,{hints:!1})),$task.fetch(t).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>e(t));else if(this.isNode()){this.initGotEnv(t);const{url:s,...i}=t;this.got.post(s,i).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>{const{message:s,response:i}=t;e(s,i,i&&i.body)})}}time(t){let e={"M+":(new Date).getMonth()+1,"d+":(new Date).getDate(),"H+":(new Date).getHours(),"m+":(new Date).getMinutes(),"s+":(new Date).getSeconds(),"q+":Math.floor(((new Date).getMonth()+3)/3),S:(new Date).getMilliseconds()};/(y+)/.test(t)&&(t=t.replace(RegExp.$1,((new Date).getFullYear()+"").substr(4-RegExp.$1.length)));for(let s in e)new RegExp("("+s+")").test(t)&&(t=t.replace(RegExp.$1,1==RegExp.$1.length?e[s]:("00"+e[s]).substr((""+e[s]).length)));return t}msg(e=t,s="",i="",r){const o=t=>{if(!t)return t;if("string"==typeof t)return this.isLoon()?t:this.isQuanX()?{"open-url":t}:this.isSurge()?{url:t}:void 0;if("object"==typeof t){if(this.isLoon()){let e=t.openUrl||t.url||t["open-url"],s=t.mediaUrl||t["media-url"];return{openUrl:e,mediaUrl:s}}if(this.isQuanX()){let e=t["open-url"]||t.url||t.openUrl,s=t["media-url"]||t.mediaUrl;return{"open-url":e,"media-url":s}}if(this.isSurge()){let e=t.url||t.openUrl||t["open-url"];return{url:e}}}};this.isMute||(this.isSurge()||this.isLoon()?$notification.post(e,s,i,o(r)):this.isQuanX()&&$notify(e,s,i,o(r)));let h=["","==============\ud83d\udce3\u7cfb\u7edf\u901a\u77e5\ud83d\udce3=============="];h.push(e),s&&h.push(s),i&&h.push(i),console.log(h.join("\n")),this.logs=this.logs.concat(h)}log(...t){t.length>0&&(this.logs=[...this.logs,...t]),console.log(t.join(this.logSeparator))}logErr(t,e){const s=!this.isSurge()&&!this.isQuanX()&&!this.isLoon();s?this.log("",`\u2757\ufe0f${this.name}, \u9519\u8bef!`,t.stack):this.log("",`\u2757\ufe0f${this.name}, \u9519\u8bef!`,t)}wait(t){return new Promise(e=>setTimeout(e,t))}done(t={}){const e=(new Date).getTime(),s=(e-this.startTime)/1e3;this.log("",`\ud83d\udd14${this.name}, \u7ed3\u675f! \ud83d\udd5b ${s} \u79d2`),this.log(),(this.isSurge()||this.isQuanX()||this.isLoon())&&$done(t)}}(t,e)} diff --git a/Task/moji.js b/Task/moji.js new file mode 100644 index 0000000000..697b4fce04 --- /dev/null +++ b/Task/moji.js @@ -0,0 +1,292 @@ +/* +支持boxjs手动修改位置,可直接输入中文地区名 +更新时间 2020-12-19 14:36 +*/ +const $ = new Env('墨迹天气') +const City = encodeURIComponent($.getdata('city')||"北京") //可在此处修改城市 +const j = $.getdata('citynum')||"1"; +let reduction = $.getdata('cut') || 'false'; //日志 +let daylys = $.getdata('day_desc') || 'true', //每日天气 + hourlys = $.getdata('hour_desc') || 'false', //小时预报 + indexs = $.getdata('index_desc') || 'false'; //生活指数 + fortys = $.getdata('forty_desc') || 'false'; //40天预告 +let Alerts = ""; + +!(async() => { + await SearchCity(); + await fortyReport(); + await Weather(); + await TodayReport(); + await showmsg() + })() + .catch((e) => $.logErr(e)) + .finally(() => $.done()) + +function Weather() { + return new Promise((resolve, reject) =>{ + let weatherurl = { + url: `https://co.moji.com/api/weather2/weather?lang=zh&city=${cityid}` + } + $.get(weatherurl, (error, response, data) => { + try { + $.weather = JSON.parse(data); + } catch (e) { + $.logErr(e, resp); + } finally { + resolve() + } + }) + }) +} + +function fortyReport() { + return new Promise((resolve, reject) =>{ + let fortyurl = { + url: `https://h5ctywhr.api.moji.com/fc40`, + headers: {'Host': 'h5ctywhr.api.moji.com',}, + body: `{"cityId": ${cityid},"cityType":${cityType}}` + } + $.post(fortyurl, (error, response, data) => { + try { + $.forty = JSON.parse(data) + realFeel = $.forty.condition.realFeel + forDay40 = $.forty.forecastDays.forecastDay40.fallTrendDesc[0] ? $.forty.forecastDays.forecastDay40.fallTrendDesc[0].desc:"" + temp40 = $.forty.forecastDays.forecastDay40.tempTrendDesc[0] ? $.forty.forecastDays.forecastDay40.tempTrendDesc[0].desc:"" + Festival = $.forty.forecastDays.forecastDay[1].festival + } catch (e) { + $.logErr(e, resp); + } finally { + resolve() + } + }) + }) +} + +function Indexs() { + return new Promise((resolve, reject) =>{ + let indexsurl = { + url: `https://h5ctywhr.api.moji.com/indexDetail?cityId=${cityid}`, + headers: {}, + body: `{"cityId": ${cityid},"cityType":${cityType}}` + } + $.post(indexsurl, (error, response, data) => { +try { + $.index = JSON.parse(data); + } catch (e) { + $.logErr(e, resp); + } finally { + resolve() + } + }) + }) +} + +function SearchCity() { + return new Promise((resolve) =>{ + let cityurl = { + url: `https://ssch.api.moji.com/citymanage/json/h5/searchCity?keyWord=${City}`, + headers: {}, + } + $.post(cityurl, (error, response, data) => { + let result = JSON.parse(data) + if(result.city_list.length>0 && j<= result.city_list.length){ + console.log("城市或者地区名称及ID序号") + for(i=0; i0){ + Alerts = '\n【气象预警】'+"预警级别: "+$.weather.data.alerts[0].level+'\n '+$.weather.data.alerts[0].content + } + $.desc = " 当天温度: "+daytemp+" 实时温度🌡:"+nowtemp+"\n " +` 实时天气: ${today_Skycon}`+" 风速🌪: "+ windDirection + nowwindval +"级" + windSpeed(nowwindval)+ "\n 空气质量🌬: "+aqidesc+" 湿度☔️: "+nowhum+Alerts +'\n' +} + +async function showmsg() { + if(daylys == 'true'){ + $.desc += "【每周天气】\n" + await WeekReport() + } + if(hourlys == 'true'){ + $.desc += "【未来6小时变化预报】\n" + await HourlyReport() + } + if (indexs== 'true'){ + $.desc += "【生活指数】\n" + await Indexs(); + await IndexReport() + } + if (fortys == 'true'){ + $.desc += "【40天预告】\n "+forDay40+temp40 + } + $.sub = "【今日天气】" +`${mapSkycon(nowweather)[0]}` + $.msg($.weather.data.city +"天气预报 "+$.weather.data.forecast_day[0].predict_date +$.weather.data.forecast_day[0].predict_week +" "+Festival,$.sub, $.desc,{"media-url": `${mapSkycon(nowweather)[1]}` + }) +} + +function Env(t,e){class s{constructor(t){this.env=t}send(t,e="GET"){t="string"==typeof t?{url:t}:t;let s=this.get;return"POST"===e&&(s=this.post),new Promise((e,i)=>{s.call(this,t,(t,s,r)=>{t?i(t):e(s)})})}get(t){return this.send.call(this.env,t)}post(t){return this.send.call(this.env,t,"POST")}}return new class{constructor(t,e){this.name=t,this.http=new s(this),this.data=null,this.dataFile="box.dat",this.logs=[],this.isMute=!1,this.isNeedRewrite=!1,this.logSeparator="\n",this.startTime=(new Date).getTime(),Object.assign(this,e),this.log("",`\ud83d\udd14${this.name}, \u5f00\u59cb!`)}isNode(){return"undefined"!=typeof module&&!!module.exports}isQuanX(){return"undefined"!=typeof $task}isSurge(){return"undefined"!=typeof $httpClient&&"undefined"==typeof $loon}isLoon(){return"undefined"!=typeof $loon}toObj(t,e=null){try{return JSON.parse(t)}catch{return e}}toStr(t,e=null){try{return JSON.stringify(t)}catch{return e}}getjson(t,e){let s=e;const i=this.getdata(t);if(i)try{s=JSON.parse(this.getdata(t))}catch{}return s}setjson(t,e){try{return this.setdata(JSON.stringify(t),e)}catch{return!1}}getScript(t){return new Promise(e=>{this.get({url:t},(t,s,i)=>e(i))})}runScript(t,e){return new Promise(s=>{let i=this.getdata("@chavy_boxjs_userCfgs.httpapi");i=i?i.replace(/\n/g,"").trim():i;let r=this.getdata("@chavy_boxjs_userCfgs.httpapi_timeout");r=r?1*r:20,r=e&&e.timeout?e.timeout:r;const[o,h]=i.split("@"),a={url:`http://${h}/v1/scripting/evaluate`,body:{script_text:t,mock_type:"cron",timeout:r},headers:{"X-Key":o,Accept:"*/*"}};this.post(a,(t,e,i)=>s(i))}).catch(t=>this.logErr(t))}loaddata(){if(!this.isNode())return{};{this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(this.dataFile),e=this.path.resolve(process.cwd(),this.dataFile),s=this.fs.existsSync(t),i=!s&&this.fs.existsSync(e);if(!s&&!i)return{};{const i=s?t:e;try{return JSON.parse(this.fs.readFileSync(i))}catch(t){return{}}}}}writedata(){if(this.isNode()){this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(this.dataFile),e=this.path.resolve(process.cwd(),this.dataFile),s=this.fs.existsSync(t),i=!s&&this.fs.existsSync(e),r=JSON.stringify(this.data);s?this.fs.writeFileSync(t,r):i?this.fs.writeFileSync(e,r):this.fs.writeFileSync(t,r)}}lodash_get(t,e,s){const i=e.replace(/\[(\d+)\]/g,".$1").split(".");let r=t;for(const t of i)if(r=Object(r)[t],void 0===r)return s;return r}lodash_set(t,e,s){return Object(t)!==t?t:(Array.isArray(e)||(e=e.toString().match(/[^.[\]]+/g)||[]),e.slice(0,-1).reduce((t,s,i)=>Object(t[s])===t[s]?t[s]:t[s]=Math.abs(e[i+1])>>0==+e[i+1]?[]:{},t)[e[e.length-1]]=s,t)}getdata(t){let e=this.getval(t);if(/^@/.test(t)){const[,s,i]=/^@(.*?)\.(.*?)$/.exec(t),r=s?this.getval(s):"";if(r)try{const t=JSON.parse(r);e=t?this.lodash_get(t,i,""):e}catch(t){e=""}}return e}setdata(t,e){let s=!1;if(/^@/.test(e)){const[,i,r]=/^@(.*?)\.(.*?)$/.exec(e),o=this.getval(i),h=i?"null"===o?null:o||"{}":"{}";try{const e=JSON.parse(h);this.lodash_set(e,r,t),s=this.setval(JSON.stringify(e),i)}catch(e){const o={};this.lodash_set(o,r,t),s=this.setval(JSON.stringify(o),i)}}else s=this.setval(t,e);return s}getval(t){return this.isSurge()||this.isLoon()?$persistentStore.read(t):this.isQuanX()?$prefs.valueForKey(t):this.isNode()?(this.data=this.loaddata(),this.data[t]):this.data&&this.data[t]||null}setval(t,e){return this.isSurge()||this.isLoon()?$persistentStore.write(t,e):this.isQuanX()?$prefs.setValueForKey(t,e):this.isNode()?(this.data=this.loaddata(),this.data[e]=t,this.writedata(),!0):this.data&&this.data[e]||null}initGotEnv(t){this.got=this.got?this.got:require("got"),this.cktough=this.cktough?this.cktough:require("tough-cookie"),this.ckjar=this.ckjar?this.ckjar:new this.cktough.CookieJar,t&&(t.headers=t.headers?t.headers:{},void 0===t.headers.Cookie&&void 0===t.cookieJar&&(t.cookieJar=this.ckjar))}get(t,e=(()=>{})){t.headers&&(delete t.headers["Content-Type"],delete t.headers["Content-Length"]),this.isSurge()||this.isLoon()?(this.isSurge()&&this.isNeedRewrite&&(t.headers=t.headers||{},Object.assign(t.headers,{"X-Surge-Skip-Scripting":!1})),$httpClient.get(t,(t,s,i)=>{!t&&s&&(s.body=i,s.statusCode=s.status),e(t,s,i)})):this.isQuanX()?(this.isNeedRewrite&&(t.opts=t.opts||{},Object.assign(t.opts,{hints:!1})),$task.fetch(t).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>e(t))):this.isNode()&&(this.initGotEnv(t),this.got(t).on("redirect",(t,e)=>{try{if(t.headers["set-cookie"]){const s=t.headers["set-cookie"].map(this.cktough.Cookie.parse).toString();this.ckjar.setCookieSync(s,null),e.cookieJar=this.ckjar}}catch(t){this.logErr(t)}}).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>{const{message:s,response:i}=t;e(s,i,i&&i.body)}))}post(t,e=(()=>{})){if(t.body&&t.headers&&!t.headers["Content-Type"]&&(t.headers["Content-Type"]="application/x-www-form-urlencoded"),t.headers&&delete t.headers["Content-Length"],this.isSurge()||this.isLoon())this.isSurge()&&this.isNeedRewrite&&(t.headers=t.headers||{},Object.assign(t.headers,{"X-Surge-Skip-Scripting":!1})),$httpClient.post(t,(t,s,i)=>{!t&&s&&(s.body=i,s.statusCode=s.status),e(t,s,i)});else if(this.isQuanX())t.method="POST",this.isNeedRewrite&&(t.opts=t.opts||{},Object.assign(t.opts,{hints:!1})),$task.fetch(t).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>e(t));else if(this.isNode()){this.initGotEnv(t);const{url:s,...i}=t;this.got.post(s,i).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>{const{message:s,response:i}=t;e(s,i,i&&i.body)})}}time(t){let e={"M+":(new Date).getMonth()+1,"d+":(new Date).getDate(),"H+":(new Date).getHours(),"m+":(new Date).getMinutes(),"s+":(new Date).getSeconds(),"q+":Math.floor(((new Date).getMonth()+3)/3),S:(new Date).getMilliseconds()};/(y+)/.test(t)&&(t=t.replace(RegExp.$1,((new Date).getFullYear()+"").substr(4-RegExp.$1.length)));for(let s in e)new RegExp("("+s+")").test(t)&&(t=t.replace(RegExp.$1,1==RegExp.$1.length?e[s]:("00"+e[s]).substr((""+e[s]).length)));return t}msg(e=t,s="",i="",r){const o=t=>{if(!t)return t;if("string"==typeof t)return this.isLoon()?t:this.isQuanX()?{"open-url":t}:this.isSurge()?{url:t}:void 0;if("object"==typeof t){if(this.isLoon()){let e=t.openUrl||t.url||t["open-url"],s=t.mediaUrl||t["media-url"];return{openUrl:e,mediaUrl:s}}if(this.isQuanX()){let e=t["open-url"]||t.url||t.openUrl,s=t["media-url"]||t.mediaUrl;return{"open-url":e,"media-url":s}}if(this.isSurge()){let e=t.url||t.openUrl||t["open-url"];return{url:e}}}};this.isMute||(this.isSurge()||this.isLoon()?$notification.post(e,s,i,o(r)):this.isQuanX()&&$notify(e,s,i,o(r)));let h=["","==============\ud83d\udce3\u7cfb\u7edf\u901a\u77e5\ud83d\udce3=============="];h.push(e),s&&h.push(s),i&&h.push(i),console.log(h.join("\n")),this.logs=this.logs.concat(h)}log(...t){t.length>0&&(this.logs=[...this.logs,...t]),console.log(t.join(this.logSeparator))}logErr(t,e){const s=!this.isSurge()&&!this.isQuanX()&&!this.isLoon();s?this.log("",`\u2757\ufe0f${this.name}, \u9519\u8bef!`,t.stack):this.log("",`\u2757\ufe0f${this.name}, \u9519\u8bef!`,t)}wait(t){return new Promise(e=>setTimeout(e,t))}done(t={}){const e=(new Date).getTime(),s=(e-this.startTime)/1e3;this.log("",`\ud83d\udd14${this.name}, \u7ed3\u675f! \ud83d\udd5b ${s} \u79d2`),this.log(),(this.isSurge()||this.isQuanX()||this.isLoon())&&$done(t)}}(t,e)} diff --git a/Task/package.json b/Task/package.json index e8a427d084..64ae633998 100644 --- a/Task/package.json +++ b/Task/package.json @@ -19,12 +19,8 @@ "homepage": "https://github.com/Sunert/Scripts#readme", "dependencies": { "crypto-js": "^4.0.0", - "got": "^11.5.1", + "got": "^11.7.0", "http-server": "^0.12.3", - "node-schedule": "^1.3.2", - "tough-cookie": "^4.0.0", - "download": "^8.0.0", - "request": "^2.88.2", - "request-promise": "^4.2.5" + "tough-cookie": "^4.0.0" } } diff --git a/Task/sendNotify.js b/Task/sendNotify.js index 040fec63fb..7b2e668b00 100644 --- a/Task/sendNotify.js +++ b/Task/sendNotify.js @@ -1,39 +1,85 @@ -// 感谢lxk0301大佬,本代码根据@lxk0301大佬编写的代码及教程修改 - +/* +本仓库借用Lxk0301大佬发送通知脚本,感谢@lxk0301 +已注释所有未提供KEY的日志,如有需要自行添加 + * @Author: LXK9301 https://github.com/LXK9301 + * @Date: 2020-08-19 16:12:40 + * @Last Modified by: LXK9301 + * @Last Modified time: 2021-1-7 17:52:54 + */ +const querystring = require("querystring"); const $ = new Env(); +// =======================================微信server酱通知设置区域=========================================== //此处填你申请的SCKEY. -//注:此处设置github action用户填写到Settings-Secrets里面(Name输入PUSH_KEY) +//(环境变量名 PUSH_KEY) let SCKEY = ''; + +// =======================================QQ酷推通知设置区域=========================================== +//此处填你申请的SKEY(具体详见文档 https://cp.xuthus.cc/) +//(环境变量名 QQ_SKEY) +let QQ_SKEY = ''; +//此处填写私聊或群组推送,默认私聊(send[私聊]、group[群聊]、wx[个微]、ww[企微]、email[邮件]) +let QQ_MODE = 'send'; + +// =======================================Bark App通知设置区域=========================================== //此处填你BarkAPP的信息(IP/设备码,例如:https://api.day.app/XXXXXXXX) -//注:此处设置github action用户填写到Settings-Secrets里面(Name输入BARK_PUSH) let BARK_PUSH = ''; //BARK app推送铃声,铃声列表去APP查看复制填写 -//注:此处设置github action用户填写到Settings-Secrets里面(Name输入BARK_SOUND , Value输入app提供的铃声名称,例如:birdsong) let BARK_SOUND = ''; + +// =======================================telegram机器人通知设置区域=========================================== //此处填你telegram bot 的Token,例如:1077xxx4424:AAFjv0FcqxxxxxxgEMGfi22B4yh15R5uw -//注:此处设置github action用户填写到Settings-Secrets里面(Name输入TG_BOT_TOKEN) +//(环境变量名 TG_BOT_TOKEN) let TG_BOT_TOKEN = ''; //此处填你接收通知消息的telegram用户的id,例如:129xxx206 -//注:此处设置github action用户填写到Settings-Secrets里面(Name输入TG_USER_ID) +//(环境变量名 TG_USER_ID) let TG_USER_ID = ''; +// =======================================钉钉机器人通知设置区域=========================================== //此处填你钉钉 bot 的webhook,例如:5a544165465465645d0f31dca676e7bd07415asdasd -//注:此处设置github action用户填写到Settings-Secrets里面(Name输入DD_BOT_TOKEN) +//(环境变量名 DD_BOT_TOKEN) let DD_BOT_TOKEN = ''; //密钥,机器人安全设置页面,加签一栏下面显示的SEC开头的字符串 let DD_BOT_SECRET = ''; -//以下为脚本运行通知开关,true为不推送,false为推送通知 -let txnewsNotifyControl = false;//(默认腾讯新闻脚本推送通知) -let youthNotifyControl = false;//(默认中青脚本推送通知) +// =======================================企业微信机器人通知设置区域=========================================== +//此处填你企业微信机器人的 webhook(详见文档 https://work.weixin.qq.com/api/doc/90000/90136/91770),例如:693a91f6-7xxx-4bc4-97a0-0ec2sifa5aaa +//(环境变量名 QYWX_KEY) +let QYWX_KEY = ''; + +// =======================================企业微信应用消息通知设置区域=========================================== +//此处填你企业微信应用消息的 值(详见文档 https://work.weixin.qq.com/api/doc/90000/90135/90236),依次填上corpid的值,corpsecret的值,touser的值,agentid的值,素材库图片id(见https://github.com/LXK9301/jd_scripts/issues/519) 注意用,号隔开,例如:wwcff56746d9adwers,B-791548lnzXBE6_BWfxdf3kSTMJr9vFEPKAbh6WERQ,mingcheng,1000001,2COXgjH2UIfERF2zxrtUOKgQ9XklUqMdGSWLBoW_lSDAdafat +//corpid的值,corpsecret的值,touser的值,agentid的值,素材库图片id的获取,可查看此教程(http://note.youdao.com/s/HMiudGkb) +//增加一个选择推送消息类型,用图文消息直接填写素材库图片id的值,用卡片消息就填写0(就是数字零) +//(环境变量名 QYWX_AM) +let QYWX_AM = ''; -let dsjNotifyControl = true;//(默认电视家脚本推送不通知) +// =======================================iGot聚合推送通知设置区域=========================================== +//此处填您iGot的信息(推送key,例如:https://push.hellyw.com/XXXXXXXX) +let IGOT_PUSH_KEY = ''; +// =======================================push+设置区域======================================= +//官方文档:https://pushplus.hxtrip.com/ +//PUSH_PLUS_TOKEN:微信扫码登录后一对一推送或一对多推送下面的token(您的Token),不提供PUSH_PLUS_USER则默认为一对一推送 +//PUSH_PLUS_USER: 一对多推送的"群组编码"(一对多推送下面->您的群组(如无则新建)->群组编码,如果您是创建群组人。也需点击"查看二维码"扫描绑定,否则不能接受群组消息推送) +let PUSH_PLUS_TOKEN = ''; +let PUSH_PLUS_USER = ''; + +//==========================云端环境变量的判断与接收========================= if (process.env.PUSH_KEY) { SCKEY = process.env.PUSH_KEY; } + +if (process.env.QQ_SKEY) { + QQ_SKEY = process.env.QQ_SKEY; +} + +if (process.env.QQ_MODE) { + QQ_MODE = process.env.QQ_MODE; +} + + if (process.env.BARK_PUSH) { if(process.env.BARK_PUSH.indexOf('https') > -1 || process.env.BARK_PUSH.indexOf('http') > -1) { //兼容BARK自建用户 @@ -63,25 +109,49 @@ if (process.env.DD_BOT_TOKEN) { DD_BOT_SECRET = process.env.DD_BOT_SECRET; } } -if (process.env.YOUTH_NOTIFY_CONTROL && process.env.YOUTH_NOTIFY_CONTROL==false) { - youthNotifyControl = process.env.YOUTH_NOTIFY_CONTROL; + +if (process.env.QYWX_KEY) { + QYWX_KEY = process.env.QYWX_KEY; } -if (process.env.TXNEWS_NOTIFY_CONTROL && process.env.TXNEWS_NOTIFY_CONTROL==false) { - txnewsNotifyControl = process.env.TXNEWS_NOTIFY_CONTROL; + +if (process.env.QYWX_AM) { + QYWX_AM = process.env.QYWX_AM; } -if (process.env.DSJ_NOTIFY_CONTROL && process.env.DSJ_NOTIFY_CONTROL==false) { - dsjNotifyControl = process.env.DSJ_NOTIFY_CONTROL; + +if (process.env.IGOT_PUSH_KEY) { + IGOT_PUSH_KEY = process.env.IGOT_PUSH_KEY } -async function sendNotify(text, desp) { - //提供三种通知 - await serverNotify(text, desp); - await BarkNotify(text, desp); - await tgBotNotify(text, desp); - await ddBotNotify(text, desp) +if (process.env.PUSH_PLUS_TOKEN) { + PUSH_PLUS_TOKEN = process.env.PUSH_PLUS_TOKEN; +} +if (process.env.PUSH_PLUS_USER) { + PUSH_PLUS_USER = process.env.PUSH_PLUS_USER; +} +//==========================云端环境变量的判断与接收========================= + + +async function sendNotify(text, desp, params = {}) { + //提供7种通知 + //desp += `\n本脚本开源免费使用 By:https://github.com/LXK9301/jd_scripts`; + await Promise.all([ + serverNotify(text, desp),//微信server酱 + pushPlusNotify(text, desp)//pushplus(推送加) + ]) + //由于上述两种微信通知需点击进去才能查看到详情,故text(标题内容)携带了账号序号以及昵称信息,方便不点击也可知道是哪个京东哪个活动 + text = text.match(/.*?(?=\s?-)/g) ? text.match(/.*?(?=\s?-)/g)[0] : text; + await Promise.all([ + BarkNotify(text, desp, params),//iOS Bark APP + tgBotNotify(text, desp),//telegram 机器人 + ddBotNotify(text, desp),//钉钉机器人 + qywxBotNotify(text, desp), //企业微信机器人 + qywxamNotify(text, desp), //企业微信应用消息推送 + iGotNotify(text, desp, params),//iGot + CoolPush(text, desp)//QQ酷推 + ]) } -function serverNotify(text, desp) { +function serverNotify(text, desp, timeout = 2100) { return new Promise(resolve => { if (SCKEY) { //微信server酱推送通知一个\n不会换行,需要两个\n才能换行,故做此替换 @@ -93,16 +163,96 @@ function serverNotify(text, desp) { 'Content-Type': 'application/x-www-form-urlencoded' } } + setTimeout(() => { + $.post(options, (err, resp, data) => { + try { + if (err) { + console.log('发送通知调用API失败!!\n') + console.log(err); + } else { + data = JSON.parse(data); + if (data.errno === 0) { + console.log('server酱发送通知消息成功\n') + } else if (data.errno === 1024) { + // 一分钟内发送相同的内容会触发 + console.log(`server酱发送通知消息异常: ${data.errmsg}\n`) + } else { + console.log(`server酱发送通知消息异常\n${JSON.stringify(data)}`) + } + } + } catch (e) { + $.logErr(e, resp); + } finally { + resolve(data); + } + }) + }, timeout) + } else { + //console.log('您未提供server酱的SCKEY,取消微信推送消息通知\n'); + resolve() + } + }) +} + +function CoolPush(text, desp) { + return new Promise(resolve => { + if (QQ_SKEY) { + let options = { + url: `https://push.xuthus.cc/${QQ_MODE}/${QQ_SKEY}`, + headers: { + 'Content-Type': 'application/json' + } + } + + // 已知敏感词 + text = text.replace(/京豆/g, "豆豆"); + desp = desp.replace(/京豆/g, ""); + desp = desp.replace(/🐶/g, ""); + desp = desp.replace(/红包/g, "H包"); + + switch (QQ_MODE) { + case "email": + options.json = { + "t": text, + "c": desp, + }; + break; + default: + options.body = `${text}\n\n${desp}`; + } + + let pushMode = function(t) { + switch (t){ + case "send": + return "个人"; + case "group": + return "QQ群"; + case "wx": + return "微信"; + case "ww": + return "企业微信"; + case "email": + return "邮件"; + default: + return "未知方式" + } + } + $.post(options, (err, resp, data) => { try { if (err) { - console.log('\n发送通知调用API失败!!\n') + console.log(`发送${pushMode(QQ_MODE)}通知调用API失败!!\n`) + console.log(err); } else { data = JSON.parse(data); - if (data.errno === 0) { - console.log('\nserver酱发送通知消息成功\n') - } else if (data.errno === 1024) { - console.log('\nPUSH_KEY 错误\n') + if (data.code === 200) { + console.log(`酷推发送${pushMode(QQ_MODE)}通知消息成功\n`) + } else if (data.code === 400) { + console.log(`QQ酷推(Cool Push)发送${pushMode(QQ_MODE)}推送失败:${data.msg}\n`) + } else if (data.code === 503) { + console.log(`QQ酷推出错,${data.message}:${data.data}\n`) + }else{ + console.log(`酷推推送异常: ${JSON.stringify(data)}`); } } } catch (e) { @@ -112,28 +262,32 @@ function serverNotify(text, desp) { } }) } else { - console.log('\n您未提供server酱的SCKEY,取消微信推送消息通知\n'); + //console.log('您未提供酷推的SKEY,取消QQ推送消息通知\n'); resolve() } }) } -function BarkNotify(text, desp) { +function BarkNotify(text, desp, params={}) { return new Promise(resolve => { if (BARK_PUSH) { const options = { - url: `${BARK_PUSH}/${encodeURIComponent(text)}/${encodeURIComponent(desp)}?sound=${BARK_SOUND}`, + url: `${BARK_PUSH}/${encodeURIComponent(text)}/${encodeURIComponent(desp)}?sound=${BARK_SOUND}&${querystring.stringify(params)}`, + headers: { + 'Content-Type': 'application/x-www-form-urlencoded' + } } $.get(options, (err, resp, data) => { try { if (err) { - console.log('\nBark APP发送通知调用API失败!!\n') + console.log('Bark APP发送通知调用API失败!!\n') + console.log(err); } else { data = JSON.parse(data); if (data.code === 200) { - console.log('\nBark APP发送通知消息成功\n') + console.log('Bark APP发送通知消息成功\n') } else { - console.log(`\n${data.message}\n`); + console.log(`${data.message}\n`); } } } catch (e) { @@ -143,7 +297,7 @@ function BarkNotify(text, desp) { } }) } else { - console.log('\n您未提供Bark的APP推送BARK_PUSH,取消Bark推送消息通知\n'); + //console.log('您未提供Bark的APP推送BARK_PUSH,取消Bark推送消息通知\n'); resolve() } }) @@ -154,23 +308,36 @@ function tgBotNotify(text, desp) { if (TG_BOT_TOKEN && TG_USER_ID) { const options = { url: `https://api.telegram.org/bot${TG_BOT_TOKEN}/sendMessage`, - body: `chat_id=${TG_USER_ID}&text=${text}\n\n${desp}`, + body: `chat_id=${TG_USER_ID}&text=${text}\n\n${desp}&disable_web_page_preview=true`, headers: { 'Content-Type': 'application/x-www-form-urlencoded' } } + if (process.env.TG_PROXY_HOST && process.env.TG_PROXY_PORT) { + const tunnel = require("tunnel"); + const agent = { + https: tunnel.httpsOverHttp({ + proxy: { + host: process.env.TG_PROXY_HOST, + port: process.env.TG_PROXY_PORT * 1 + } + }) + } + Object.assign(options, { agent }) + } $.post(options, (err, resp, data) => { try { if (err) { - console.log('\ntelegram发送通知消息失败!!\n') + console.log('telegram发送通知消息失败!!\n') + console.log(err); } else { data = JSON.parse(data); if (data.ok) { - console.log('\nTelegram发送通知消息完成。\n') + console.log('Telegram发送通知消息完成。\n') } else if (data.error_code === 400) { - console.log('\n请主动给bot发送一条消息并检查接收用户ID是否正确。\n') + console.log('请主动给bot发送一条消息并检查接收用户ID是否正确。\n') } else if (data.error_code === 401){ - console.log('\nTelegram bot token 填写错误。\n') + console.log('Telegram bot token 填写错误。\n') } } } catch (e) { @@ -180,7 +347,7 @@ function tgBotNotify(text, desp) { } }) } else { - console.log('\n您未提供telegram机器人推送所需的TG_BOT_TOKEN和TG_USER_ID,取消telegram推送消息通知\n'); + //console.log('您未提供telegram机器人推送所需的TG_BOT_TOKEN和TG_USER_ID,取消telegram推送消息通知\n'); resolve() } }) @@ -209,14 +376,14 @@ function ddBotNotify(text, desp) { $.post(options, (err, resp, data) => { try { if (err) { - console.log('\n钉钉发送通知消息失败!!\n') + console.log('钉钉发送通知消息失败!!\n') console.log(err); } else { data = JSON.parse(data); if (data.errcode === 0) { - console.log('\n钉钉发送通知消息完成。\n') + console.log('钉钉发送通知消息完成。\n') } else { - console.log(`\n${data.errmsg}\n`) + console.log(`${data.errmsg}\n`) } } } catch (e) { @@ -229,14 +396,185 @@ function ddBotNotify(text, desp) { $.post(options, (err, resp, data) => { try { if (err) { - console.log('\n钉钉发送通知消息失败!!\n') + console.log('钉钉发送通知消息失败!!\n') + console.log(err); + } else { + data = JSON.parse(data); + if (data.errcode === 0) { + console.log('钉钉发送通知消息完成。\n') + } else { + console.log(`${data.errmsg}\n`) + } + } + } catch (e) { + $.logErr(e, resp); + } finally { + resolve(data); + } + }) + } else { + //console.log('您未提供钉钉机器人推送所需的DD_BOT_TOKEN或者DD_BOT_SECRET,取消钉钉推送消息通知\n'); + resolve() + } + }) +} + +function qywxBotNotify(text, desp) { + return new Promise(resolve => { + const options = { + url: `https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=${QYWX_KEY}`, + json: { + msgtype: 'text', + text: { + content: ` ${text}\n\n${desp}`, + }, + }, + headers: { + 'Content-Type': 'application/json', + }, + }; + if (QYWX_KEY) { + $.post(options, (err, resp, data) => { + try { + if (err) { + console.log('企业微信发送通知消息失败!!\n'); console.log(err); } else { data = JSON.parse(data); if (data.errcode === 0) { - console.log('\n钉钉发送通知消息完成。\n') + console.log('企业微信发送通知消息完成。\n'); + } else { + console.log(`${data.errmsg}\n`); + } + } + } catch (e) { + $.logErr(e, resp); + } finally { + resolve(data); + } + }); + } else { + //console.log('您未提供企业微信机器人推送所需的QYWX_KEY,取消企业微信推送消息通知\n'); + resolve(); + } + }); +} + +function qywxamNotify(text, desp) { + return new Promise(resolve => { + if (QYWX_AM) { + var QYWX_AM_AY = QYWX_AM.split(','); + const options_accesstoken = { + url: `https://qyapi.weixin.qq.com/cgi-bin/gettoken`, + json: { + corpid:`${QYWX_AM_AY[0]}`, + corpsecret:`${QYWX_AM_AY[1]}`, + }, + headers: { + 'Content-Type': 'application/json', + }, + }; + $.post(options_accesstoken, (err, resp, data) => { + html=desp.replace(/\n/g,"
") + var json = JSON.parse(data); + accesstoken = json.access_token; + const options_textcard = { + url: `https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=${accesstoken}`, + json: { + touser:`${QYWX_AM_AY[2]}`, + agentid:`${QYWX_AM_AY[3]}`, + msgtype: 'textcard', + textcard: { + title: `${text}`, + description: `${desp}`, + url: '127.0.0.1', + btntxt: '更多' + }, + safe:'0', + }, + headers: { + 'Content-Type': 'application/json', + }, + }; + const options_mpnews = { + url: `https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=${accesstoken}`, + json: { + touser:`${QYWX_AM_AY[2]}`, + agentid:`${QYWX_AM_AY[3]}`, + msgtype: 'mpnews', + mpnews: { + articles: [ + { + title: `${text}`, + thumb_media_id: `${QYWX_AM_AY[4]}`, + author : `智能助手` , + content_source_url: ``, + content : `${html}`, + digest: `${desp}` + } + ] + }, + safe:'0', + }, + headers: { + 'Content-Type': 'application/json', + }, + }; + $.post((QYWX_AM_AY[4]==0)?options_textcard:options_mpnews, (err, resp, data) => { + try { + if (err) { + console.log('企业微信应用消息发送通知消息失败!!\n'); + console.log(err); + } else { + data = JSON.parse(data); + if (data.errcode === 0) { + console.log('企业微信应用消息发送通知消息完成。\n'); + } else { + console.log(`${data.errmsg}\n`); + } + } + } catch (e) { + $.logErr(e, resp); + } finally { + resolve(data); + } + }); + }); + } else { + //console.log('您未提供企业微信应用消息推送所需的QYWX_AM,取消企业微信应用消息推送消息通知\n'); + resolve(); + } + }); +} + +function iGotNotify(text, desp, params={}){ + return new Promise(resolve => { + if (IGOT_PUSH_KEY) { + // 校验传入的IGOT_PUSH_KEY是否有效 + const IGOT_PUSH_KEY_REGX = new RegExp("^[a-zA-Z0-9]{24}$") + if(!IGOT_PUSH_KEY_REGX.test(IGOT_PUSH_KEY)) { + console.log('您所提供的IGOT_PUSH_KEY无效\n') + resolve() + return + } + const options = { + url: `https://push.hellyw.com/${IGOT_PUSH_KEY.toLowerCase()}`, + body: `title=${text}&content=${desp}&${querystring.stringify(params)}`, + headers: { + 'Content-Type': 'application/x-www-form-urlencoded' + } + } + $.post(options, (err, resp, data) => { + try { + if (err) { + console.log('发送通知调用API失败!!\n') + console.log(err); + } else { + if(typeof data === 'string') data = JSON.parse(data); + if (data.ret === 0) { + console.log('iGot发送通知消息成功\n') } else { - console.log(`\n${data.errmsg}\n`) + console.log(`iGot发送通知消息失败:${data.errMsg}\n`) } } } catch (e) { @@ -246,25 +584,58 @@ function ddBotNotify(text, desp) { } }) } else { - console.log('\n您未提供钉钉机器人推送所需的DD_BOT_TOKEN或者DD_BOT_SECRET,取消钉钉推送消息通知\n'); + //console.log('您未提供iGot的推送IGOT_PUSH_KEY,取消iGot推送消息通知\n'); resolve() } }) } + +function pushPlusNotify(text, desp) { + return new Promise(resolve => { + if (PUSH_PLUS_TOKEN) { + desp = desp.replace(/[\n\r]/g, '
'); // 默认为html, 不支持plaintext + const body = { + token: `${PUSH_PLUS_TOKEN}`, + title: `${text}`, + content:`${desp}`, + topic: `${PUSH_PLUS_USER}` + }; + const options = { + url: `https://pushplus.hxtrip.com/send`, + body: JSON.stringify(body), + headers: { + 'Content-Type': ' application/json' + } + } + $.post(options, (err, resp, data) => { + try { + if (err) { + console.log(`push+发送${PUSH_PLUS_USER ? '一对多' : '一对一'}通知消息失败!!\n`) + console.log(err); + } else { + data = JSON.parse(data); + if (data.code === 200) { + console.log(`push+发送${PUSH_PLUS_USER ? '一对多' : '一对一'}通知消息完成。\n`) + } else { + console.log(`push+发送${PUSH_PLUS_USER ? '一对多' : '一对一'}通知消息失败:${data.msg}\n`) + } + } + } catch (e) { + $.logErr(e, resp); + } finally { + resolve(data); + } + }) + } else { + //console.log('您未提供push+推送所需的PUSH_PLUS_TOKEN,取消push+推送消息通知\n'); + resolve() + } + }) +} + module.exports = { sendNotify, - BarkNotify, - SCKEY, - BARK_PUSH, - TG_BOT_TOKEN, - TG_USER_ID, - DD_BOT_TOKEN, - dsjNotifyControl, - txnewsNotifyControl, - youthNotifyControl, - YOUTH_NOTIFY_CONTROL, - TXNEWS_NOTIFY_CONTROL, - DSJ_NOTIFY_CONTROL + BARK_PUSH } // prettier-ignore -function Env(t,s){return new class{constructor(t,s){this.name=t,this.data=null,this.dataFile="box.dat",this.logs=[],this.logSeparator="\n",this.startTime=(new Date).getTime(),Object.assign(this,s),this.log("",`\ud83d\udd14${this.name}, \u5f00\u59cb!`)}isNode(){return"undefined"!=typeof module&&!!module.exports}isQuanX(){return"undefined"!=typeof $task}isSurge(){return"undefined"!=typeof $httpClient&&"undefined"==typeof $loon}isLoon(){return"undefined"!=typeof $loon}getScript(t){return new Promise(s=>{$.get({url:t},(t,e,i)=>s(i))})}runScript(t,s){return new Promise(e=>{let i=this.getdata("@chavy_boxjs_userCfgs.httpapi");i=i?i.replace(/\n/g,"").trim():i;let o=this.getdata("@chavy_boxjs_userCfgs.httpapi_timeout");o=o?1*o:20,o=s&&s.timeout?s.timeout:o;const[h,a]=i.split("@"),r={url:`http://${a}/v1/scripting/evaluate`,body:{script_text:t,mock_type:"cron",timeout:o},headers:{"X-Key":h,Accept:"*/*"}};$.post(r,(t,s,i)=>e(i))}).catch(t=>this.logErr(t))}loaddata(){if(!this.isNode())return{};{this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(this.dataFile),s=this.path.resolve(process.cwd(),this.dataFile),e=this.fs.existsSync(t),i=!e&&this.fs.existsSync(s);if(!e&&!i)return{};{const i=e?t:s;try{return JSON.parse(this.fs.readFileSync(i))}catch(t){return{}}}}}writedata(){if(this.isNode()){this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(this.dataFile),s=this.path.resolve(process.cwd(),this.dataFile),e=this.fs.existsSync(t),i=!e&&this.fs.existsSync(s),o=JSON.stringify(this.data);e?this.fs.writeFileSync(t,o):i?this.fs.writeFileSync(s,o):this.fs.writeFileSync(t,o)}}lodash_get(t,s,e){const i=s.replace(/\[(\d+)\]/g,".$1").split(".");let o=t;for(const t of i)if(o=Object(o)[t],void 0===o)return e;return o}lodash_set(t,s,e){return Object(t)!==t?t:(Array.isArray(s)||(s=s.toString().match(/[^.[\]]+/g)||[]),s.slice(0,-1).reduce((t,e,i)=>Object(t[e])===t[e]?t[e]:t[e]=Math.abs(s[i+1])>>0==+s[i+1]?[]:{},t)[s[s.length-1]]=e,t)}getdata(t){let s=this.getval(t);if(/^@/.test(t)){const[,e,i]=/^@(.*?)\.(.*?)$/.exec(t),o=e?this.getval(e):"";if(o)try{const t=JSON.parse(o);s=t?this.lodash_get(t,i,""):s}catch(t){s=""}}return s}setdata(t,s){let e=!1;if(/^@/.test(s)){const[,i,o]=/^@(.*?)\.(.*?)$/.exec(s),h=this.getval(i),a=i?"null"===h?null:h||"{}":"{}";try{const s=JSON.parse(a);this.lodash_set(s,o,t),e=this.setval(JSON.stringify(s),i)}catch(s){const h={};this.lodash_set(h,o,t),e=this.setval(JSON.stringify(h),i)}}else e=$.setval(t,s);return e}getval(t){return this.isSurge()||this.isLoon()?$persistentStore.read(t):this.isQuanX()?$prefs.valueForKey(t):this.isNode()?(this.data=this.loaddata(),this.data[t]):this.data&&this.data[t]||null}setval(t,s){return this.isSurge()||this.isLoon()?$persistentStore.write(t,s):this.isQuanX()?$prefs.setValueForKey(t,s):this.isNode()?(this.data=this.loaddata(),this.data[s]=t,this.writedata(),!0):this.data&&this.data[s]||null}initGotEnv(t){this.got=this.got?this.got:require("got"),this.cktough=this.cktough?this.cktough:require("tough-cookie"),this.ckjar=this.ckjar?this.ckjar:new this.cktough.CookieJar,t&&(t.headers=t.headers?t.headers:{},void 0===t.headers.Cookie&&void 0===t.cookieJar&&(t.cookieJar=this.ckjar))}get(t,s=(()=>{})){t.headers&&(delete t.headers["Content-Type"],delete t.headers["Content-Length"]),this.isSurge()||this.isLoon()?$httpClient.get(t,(t,e,i)=>{!t&&e&&(e.body=i,e.statusCode=e.status),s(t,e,i)}):this.isQuanX()?$task.fetch(t).then(t=>{const{statusCode:e,statusCode:i,headers:o,body:h}=t;s(null,{status:e,statusCode:i,headers:o,body:h},h)},t=>s(t)):this.isNode()&&(this.initGotEnv(t),this.got(t).on("redirect",(t,s)=>{try{const e=t.headers["set-cookie"].map(this.cktough.Cookie.parse).toString();this.ckjar.setCookieSync(e,null),s.cookieJar=this.ckjar}catch(t){this.logErr(t)}}).then(t=>{const{statusCode:e,statusCode:i,headers:o,body:h}=t;s(null,{status:e,statusCode:i,headers:o,body:h},h)},t=>s(t)))}post(t,s=(()=>{})){if(t.body&&t.headers&&!t.headers["Content-Type"]&&(t.headers["Content-Type"]="application/x-www-form-urlencoded"),delete t.headers["Content-Length"],this.isSurge()||this.isLoon())$httpClient.post(t,(t,e,i)=>{!t&&e&&(e.body=i,e.statusCode=e.status),s(t,e,i)});else if(this.isQuanX())t.method="POST",$task.fetch(t).then(t=>{const{statusCode:e,statusCode:i,headers:o,body:h}=t;s(null,{status:e,statusCode:i,headers:o,body:h},h)},t=>s(t));else if(this.isNode()){this.initGotEnv(t);const{url:e,...i}=t;this.got.post(e,i).then(t=>{const{statusCode:e,statusCode:i,headers:o,body:h}=t;s(null,{status:e,statusCode:i,headers:o,body:h},h)},t=>s(t))}}time(t){let s={"M+":(new Date).getMonth()+1,"d+":(new Date).getDate(),"H+":(new Date).getHours(),"m+":(new Date).getMinutes(),"s+":(new Date).getSeconds(),"q+":Math.floor(((new Date).getMonth()+3)/3),S:(new Date).getMilliseconds()};/(y+)/.test(t)&&(t=t.replace(RegExp.$1,((new Date).getFullYear()+"").substr(4-RegExp.$1.length)));for(let e in s)new RegExp("("+e+")").test(t)&&(t=t.replace(RegExp.$1,1==RegExp.$1.length?s[e]:("00"+s[e]).substr((""+s[e]).length)));return t}msg(s=t,e="",i="",o){const h=t=>!t||!this.isLoon()&&this.isSurge()?t:"string"==typeof t?this.isLoon()?t:this.isQuanX()?{"open-url":t}:void 0:"object"==typeof t&&(t["open-url"]||t["media-url"])?this.isLoon()?t["open-url"]:this.isQuanX()?t:void 0:void 0;$.isMute||(this.isSurge()||this.isLoon()?$notification.post(s,e,i,h(o)):this.isQuanX()&&$notify(s,e,i,h(o))),this.logs.push("","==============\ud83d\udce3\u7cfb\u7edf\u901a\u77e5\ud83d\udce3=============="),this.logs.push(s),e&&this.logs.push(e),i&&this.logs.push(i)}log(...t){t.length>0?this.logs=[...this.logs,...t]:console.log(this.logs.join(this.logSeparator))}logErr(t,s){const e=!this.isSurge()&&!this.isQuanX()&&!this.isLoon();e?$.log("",`\u2757\ufe0f${this.name}, \u9519\u8bef!`,t.stack):$.log("",`\u2757\ufe0f${this.name}, \u9519\u8bef!`,t)}wait(t){return new Promise(s=>setTimeout(s,t))}done(t={}){const s=(new Date).getTime(),e=(s-this.startTime)/1e3;this.log("",`\ud83d\udd14${this.name}, \u7ed3\u675f! \ud83d\udd5b ${e} \u79d2`),this.log(),(this.isSurge()||this.isQuanX()||this.isLoon())&&$done(t)}}(t,s)} \ No newline at end of file +function Env(t,s){return new class{constructor(t,s){this.name=t,this.data=null,this.dataFile="box.dat",this.logs=[],this.logSeparator="\n",this.startTime=(new Date).getTime(),Object.assign(this,s),this.log("",`\ud83d\udd14${this.name}, \u5f00\u59cb!`)}isNode(){return"undefined"!=typeof module&&!!module.exports}isQuanX(){return"undefined"!=typeof $task}isSurge(){return"undefined"!=typeof $httpClient&&"undefined"==typeof $loon}isLoon(){return"undefined"!=typeof $loon}getScript(t){return new Promise(s=>{$.get({url:t},(t,e,i)=>s(i))})}runScript(t,s){return new Promise(e=>{let i=this.getdata("@chavy_boxjs_userCfgs.httpapi");i=i?i.replace(/\n/g,"").trim():i;let o=this.getdata("@chavy_boxjs_userCfgs.httpapi_timeout");o=o?1*o:20,o=s&&s.timeout?s.timeout:o;const[h,a]=i.split("@"),r={url:`http://${a}/v1/scripting/evaluate`,body:{script_text:t,mock_type:"cron",timeout:o},headers:{"X-Key":h,Accept:"*/*"}};$.post(r,(t,s,i)=>e(i))}).catch(t=>this.logErr(t))}loaddata(){if(!this.isNode())return{};{this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(this.dataFile),s=this.path.resolve(process.cwd(),this.dataFile),e=this.fs.existsSync(t),i=!e&&this.fs.existsSync(s);if(!e&&!i)return{};{const i=e?t:s;try{return JSON.parse(this.fs.readFileSync(i))}catch(t){return{}}}}}writedata(){if(this.isNode()){this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(this.dataFile),s=this.path.resolve(process.cwd(),this.dataFile),e=this.fs.existsSync(t),i=!e&&this.fs.existsSync(s),o=JSON.stringify(this.data);e?this.fs.writeFileSync(t,o):i?this.fs.writeFileSync(s,o):this.fs.writeFileSync(t,o)}}lodash_get(t,s,e){const i=s.replace(/\[(\d+)\]/g,".$1").split(".");let o=t;for(const t of i)if(o=Object(o)[t],void 0===o)return e;return o}lodash_set(t,s,e){return Object(t)!==t?t:(Array.isArray(s)||(s=s.toString().match(/[^.[\]]+/g)||[]),s.slice(0,-1).reduce((t,e,i)=>Object(t[e])===t[e]?t[e]:t[e]=Math.abs(s[i+1])>>0==+s[i+1]?[]:{},t)[s[s.length-1]]=e,t)}getdata(t){let s=this.getval(t);if(/^@/.test(t)){const[,e,i]=/^@(.*?)\.(.*?)$/.exec(t),o=e?this.getval(e):"";if(o)try{const t=JSON.parse(o);s=t?this.lodash_get(t,i,""):s}catch(t){s=""}}return s}setdata(t,s){let e=!1;if(/^@/.test(s)){const[,i,o]=/^@(.*?)\.(.*?)$/.exec(s),h=this.getval(i),a=i?"null"===h?null:h||"{}":"{}";try{const s=JSON.parse(a);this.lodash_set(s,o,t),e=this.setval(JSON.stringify(s),i)}catch(s){const h={};this.lodash_set(h,o,t),e=this.setval(JSON.stringify(h),i)}}else e=$.setval(t,s);return e}getval(t){return this.isSurge()||this.isLoon()?$persistentStore.read(t):this.isQuanX()?$prefs.valueForKey(t):this.isNode()?(this.data=this.loaddata(),this.data[t]):this.data&&this.data[t]||null}setval(t,s){return this.isSurge()||this.isLoon()?$persistentStore.write(t,s):this.isQuanX()?$prefs.setValueForKey(t,s):this.isNode()?(this.data=this.loaddata(),this.data[s]=t,this.writedata(),!0):this.data&&this.data[s]||null}initGotEnv(t){this.got=this.got?this.got:require("got"),this.cktough=this.cktough?this.cktough:require("tough-cookie"),this.ckjar=this.ckjar?this.ckjar:new this.cktough.CookieJar,t&&(t.headers=t.headers?t.headers:{},void 0===t.headers.Cookie&&void 0===t.cookieJar&&(t.cookieJar=this.ckjar))}get(t,s=(()=>{})){t.headers&&(delete t.headers["Content-Type"],delete t.headers["Content-Length"]),this.isSurge()||this.isLoon()?$httpClient.get(t,(t,e,i)=>{!t&&e&&(e.body=i,e.statusCode=e.status),s(t,e,i)}):this.isQuanX()?$task.fetch(t).then(t=>{const{statusCode:e,statusCode:i,headers:o,body:h}=t;s(null,{status:e,statusCode:i,headers:o,body:h},h)},t=>s(t)):this.isNode()&&(this.initGotEnv(t),this.got(t).on("redirect",(t,s)=>{try{const e=t.headers["set-cookie"].map(this.cktough.Cookie.parse).toString();this.ckjar.setCookieSync(e,null),s.cookieJar=this.ckjar}catch(t){this.logErr(t)}}).then(t=>{const{statusCode:e,statusCode:i,headers:o,body:h}=t;s(null,{status:e,statusCode:i,headers:o,body:h},h)},t=>s(t)))}post(t,s=(()=>{})){if(t.body&&t.headers&&!t.headers["Content-Type"]&&(t.headers["Content-Type"]="application/x-www-form-urlencoded"),delete t.headers["Content-Length"],this.isSurge()||this.isLoon())$httpClient.post(t,(t,e,i)=>{!t&&e&&(e.body=i,e.statusCode=e.status),s(t,e,i)});else if(this.isQuanX())t.method="POST",$task.fetch(t).then(t=>{const{statusCode:e,statusCode:i,headers:o,body:h}=t;s(null,{status:e,statusCode:i,headers:o,body:h},h)},t=>s(t));else if(this.isNode()){this.initGotEnv(t);const{url:e,...i}=t;this.got.post(e,i).then(t=>{const{statusCode:e,statusCode:i,headers:o,body:h}=t;s(null,{status:e,statusCode:i,headers:o,body:h},h)},t=>s(t))}}time(t){let s={"M+":(new Date).getMonth()+1,"d+":(new Date).getDate(),"H+":(new Date).getHours(),"m+":(new Date).getMinutes(),"s+":(new Date).getSeconds(),"q+":Math.floor(((new Date).getMonth()+3)/3),S:(new Date).getMilliseconds()};/(y+)/.test(t)&&(t=t.replace(RegExp.$1,((new Date).getFullYear()+"").substr(4-RegExp.$1.length)));for(let e in s)new RegExp("("+e+")").test(t)&&(t=t.replace(RegExp.$1,1==RegExp.$1.length?s[e]:("00"+s[e]).substr((""+s[e]).length)));return t}msg(s=t,e="",i="",o){const h=t=>!t||!this.isLoon()&&this.isSurge()?t:"string"==typeof t?this.isLoon()?t:this.isQuanX()?{"open-url":t}:void 0:"object"==typeof t&&(t["open-url"]||t["media-url"])?this.isLoon()?t["open-url"]:this.isQuanX()?t:void 0:void 0;$.isMute||(this.isSurge()||this.isLoon()?$notification.post(s,e,i,h(o)):this.isQuanX()&&$notify(s,e,i,h(o))),this.logs.push("","==============\ud83d\udce3\u7cfb\u7edf\u901a\u77e5\ud83d\udce3=============="),this.logs.push(s),e&&this.logs.push(e),i&&this.logs.push(i)}log(...t){t.length>0?this.logs=[...this.logs,...t]:console.log(this.logs.join(this.logSeparator))}logErr(t,s){const e=!this.isSurge()&&!this.isQuanX()&&!this.isLoon();e?$.log("",`\u2757\ufe0f${this.name}, \u9519\u8bef!`,t.stack):$.log("",`\u2757\ufe0f${this.name}, \u9519\u8bef!`,t)}wait(t){return new Promise(s=>setTimeout(s,t))}done(t={}){const s=(new Date).getTime(),e=(s-this.startTime)/1e3;this.log("",`\ud83d\udd14${this.name}, \u7ed3\u675f! \ud83d\udd5b ${e} \u79d2`),this.log(),(this.isSurge()||this.isQuanX()||this.isLoon())&&$done(t)}}(t,s)} diff --git a/Task/sunert.boxjs.json b/Task/sunert.boxjs.json index 3054d95b53..8357ab63c0 100644 --- a/Task/sunert.boxjs.json +++ b/Task/sunert.boxjs.json @@ -1,260 +1,639 @@ { - "id": "sunert.app.sub", - "name": "Sunert 签到应用订阅", - "author": "@Sunert", - "icon": "https://avatars2.githubusercontent.com/u/47924389?s=460&u=5152f048a9e8aaa45102763a578172407c40fcc8&v=4", - "repo": "https://gitee.com/Sunert/Scripts/tree/master", + "id": "sunert.app.sub", + "author": "@Sunert", + "icon": "https://avatars2.githubusercontent.com/u/47924389?s=460&u=5152f048a9e8aaa45102763a578172407c40fcc8&v=4", + "name": "Sunert 签到应用订阅", + "repo": "https://github.com/Sunert/Scripts/tree/master", "apps": [ { - "id": "weibo", - "name": "新浪微博", - "keys": ["sy_payheader_wb", "sy_token_wb"], - "author": "@sunert", - "repo": "https://gitee.com/Sunert/Scripts/blob/master/Task/weibo.js", - "icons": ["https://raw.githubusercontent.com/Orz-3/mini/master/weibo.png", "https://raw.githubusercontent.com/Orz-3/task/master/weibo.png"], - "script": "https://gitee.com/Sunert/Scripts/raw/master/Task/weibo.js" - }, + "author": "@sunert", + "descs_html": [ + "

获取Cookie以及脚本配置请查看配置说明

", + "
", + "

其中wb_nick为账号昵称,无需另外获取,脚本运行可自动生成,wb_cookie为任务红包余额,获取后方可显示,可选,sy_token_wb为微博签到token,必选

" + ], + "keys": [ + "sy_token_wb", + "wb_cookie", + "wb_nick" + ], + "repo": "https://github.com/Sunert/Scripts/blob/master/Task/weibo.js", + "id": "weibo", + "script": "https://raw.githubusercontent.com/Sunert/Scripts/master/Task/weibo.js", + "name": "新浪微博", + "icons": [ + "https://raw.githubusercontent.com/Orz-3/mini/master/weibo.png", + "https://raw.githubusercontent.com/Orz-3/mini/master/Color/weibo.png" + ] + }, { - "id": "youth", - "name": "中青看点", - "keys": ["youthheader_zq", "read_zq", "red_zq", "readtime_zq"], - "author": "@sunert", + "author": "@sunert", + "descs_html": [ + "

获取Cookie以及脚本配置请查看配置说明

", + "
", + "

其中zq_nick、zqcash和zqcard为昵称、提现金额和早起打卡开关,无需另外获取,相关项设置后自动生成,cashurl_zq和cashbody_zq为提现请求,获取后方可自动提现,可选

" + ], + "keys": [ + "zq_nick", + "youthheader_zq", + "read_zq", + "readtime_zq", + "cashurl_zq", + "cashbody_zq", + "zqcash", + "zqcard" + ], + "repo": "https://github.com/Sunert/Scripts/blob/master/Task/youth.js", + "id": "youth", + "script": "https://raw.githubusercontent.com/Sunert/Scripts/master/Task/youth.js", "settings": [ { - "id": "notifytimes", - "name": "通知频率 (点击查看设置说明)", - "val": "", - "type": "number", - "desc": "设定通知频率,前三次为全部通知,之后转盘次数/设定频率整除时通知,如设置0为无通知,设置1为全部通知,设置其他数可整除余0时通知,默认值50" - }, - { - "id": "zqlogs", - "name": "调试日志", - "val": false, - "type": "boolean", - "desc": "调试日志开关,默认关闭" - } - ], - "repo": "https://gitee.com/Sunert/Scripts/blob/master/Task/youth.js", - "icons": ["https://raw.githubusercontent.com/Orz-3/mini/master/youth.png", "https://raw.githubusercontent.com/Orz-3/task/master/youth.png"], - "script": "https://gitee.com/Sunert/Scripts/raw/master/Task/youth.js" - }, + "id": "zqcard", + "val": "false", + "name": "打卡赚钱", + "type": "boolean", + "desc": "每日打卡报名及早起打卡" + }, + { + "id": "zqtime", + "val": "05", + "name": "打卡时间", + "type": "number", + "desc": "每日早起打卡时间" + }, + { + "id": "delay_rotary_zq", + "val": "10", + "name": "转盘时间间隔", + "type": "number", + "desc": "间隔时间设置,如1秒填1即可" + }, + { + "id": "notifytimes", + "val": "", + "name": "通知频率 (点击查看设置说明)", + "type": "number", + "desc": "设定通知频率,前三次为全部通知,之后转盘次数/设定频率整除时通知,如设置0为无通知,设置1为全部通知,设置其他数可整除余0时通知,默认值50" + }, + { + "id": "zqcash", + "val": "30", + "name": "提现金额", + "type": "radios", + "desc": "自动提现金额需和获取提现请求保持一致", + "items": [ + { + "key": "10", + "label": "10元" + }, + { + "key": "30", + "label": "30元" + }, + { + "key": "100", + "label": "100元" + } + ] + } + ], + "name": "中青看点", + "icons": [ + "https://raw.githubusercontent.com/Orz-3/mini/master/youth.png", + "https://raw.githubusercontent.com/Orz-3/mini/master/Color/youth.png" + ] + }, { - "id": "dianshijia", - "name": "电视家", - "keys": ["sy_signheader_dsj", "drawal_dsj"], - "author": "@sunert", - "repo": "https://gitee.com/Sunert/Scripts/blob/master/Task/dianshijia.js", - "icons": ["https://raw.githubusercontent.com/Orz-3/mini/master/dianshijia.png", "https://raw.githubusercontent.com/Orz-3/task/master/dianshijia.png"], - "script": "https://gitee.com/Sunert/Scripts/raw/master/Task/dianshijia.js" - }, + "author": "@sunert", + "keys": [ + "youth_start", + "youth_end" + ], + "repo": "https://github.com/Sunert/Scripts/blob/master/Task/youth_gain.js", + "id": "youthGain", + "script": "https://raw.githubusercontent.com/Sunert/Scripts/master/Task/youth_gain.js", + "name": "中青浏览赚", + "icons": [ + "https://raw.githubusercontent.com/Orz-3/mini/master/youth.png", + "https://raw.githubusercontent.com/Orz-3/mini/master/Color/youth.png" + ] + }, { - "id": "kuaishou", - "name": "快手极速版", - "keys": ["cookie_ks"], - "author": "@sunert", - "repo": "https://gitee.com/Sunert/Scripts/blob/master/Task/kuaishou.js", - "icons": ["https://raw.githubusercontent.com/Orz-3/mini/master/kuaishou.png", "https://raw.githubusercontent.com/Orz-3/task/master/kuaishou.png"], - "script": "https://gitee.com/Sunert/Scripts/raw/master/Task/kuaishou.js" - }, + "author": "@sunert", + "keys": [ + "youth_autoread", + "autotime_zq" + ], + "repo": "https://github.com/Sunert/Scripts/blob/master/Task/Youth_Read.js", + "id": "youthRead", + "script": "https://raw.githubusercontent.com/Sunert/Scripts/master/Task/Youth_Read.js", + "name": "中青自动阅读", + "icons": [ + "https://raw.githubusercontent.com/Orz-3/mini/master/youth.png", + "https://raw.githubusercontent.com/Orz-3/mini/master/Color/youth.png" + ] + }, { - "id": "sinanews", - "name": "新浪新闻", - "keys": ["sy_signurl_snews", "sy_info_snews", "sy_ck_snews", "sy_infoheader_snews"], - "author": "@sunert", - "repo": "https://gitee.com/Sunert/Scripts/blob/master/Task/sinanews.js", - "icons": ["https://raw.githubusercontent.com/Orz-3/mini/master/sinanews.png", "https://raw.githubusercontent.com/Orz-3/task/master/sinanews.png"], - "script": "https://gitee.com/Sunert/Scripts/raw/master/Task/sinanews.js" - }, + "author": "@sunert", + "keys": [ + "sy_signheader_dsj", + "drawal_dsj" + ], + "repo": "https://github.com/Sunert/Scripts/blob/master/Task/dianshijia.js", + "id": "dianshijia", + "script": "https://raw.githubusercontent.com/Sunert/Scripts/master/Task/dianshijia.js", + "settings": [ + { + "items": [ + { + "key": "55", + "label": "提现额度" + }, + { + "key": "44", + "label": "1天VIP" + }, + { + "key": "42", + "label": "1888金币" + } + ], + "id": "REWARD", + "val": "55", + "name": "额外签到奖励", + "type": "radios", + "desc": "" + } + ], + "name": "电视家", + "icons": [ + "https://raw.githubusercontent.com/Orz-3/mini/master/dianshijia.png", + "https://raw.githubusercontent.com/Orz-3/mini/master/Color/dianshijia.png" + ] + }, { - "id": "chinatelecomEnquiry", - "name": "电信套餐查询", - "keys": ["china_telecom_authToken_10000", "china_telecom_cookie"], + "author": "@sunert", + "keys": [ + "cookie_ks" + ], "settings": [ - { - "id": "Mon", - "name": "查询月份", - "val": "2020-08", - "type": "month", - "desc": "填入账单月份,可查最近六个月,本月账单下月可查" - } - ], - "author": "@sunert", - "repo": "https://gitee.com/Sunert/Scripts/blob/master/Task/telecomInfinity.js", - "icons": ["https://raw.githubusercontent.com/Orz-3/mini/master/telecominfinty.png", "https://raw.githubusercontent.com/Orz-3/task/master/telecominfinty.png"], - "script": "https://gitee.com/Sunert/Scripts/raw/master/Task/telecomInfinity.js" - }, + { + "id": "cash_nebulaks", + "val": "30", + "name": "极速版提现", + "type": "number", + "desc": "极速版提现金额,默认30" + }, + { + "id": "cash_nebulaks", + "val": "30", + "name": "极速版提现", + "type": "radios", + "items": [ + { + "key": "ALIPAY", + "label": "支付宝" + }, + { + "key": "WECHAT", + "label": "微信" + } + ], + "desc": "极速版提现金额,默认30,前提是绑定支付方式" + } + ], + "repo": "https://github.com/Sunert/Scripts/blob/master/Task/kuaishou.js", + "id": "kuaishou", + "script": "https://raw.githubusercontent.com/Sunert/Scripts/master/Task/kuaishou.js", + "name": "快手极速版", + "icons": [ + "https://raw.githubusercontent.com/Orz-3/mini/master/kuaishou.png", + "https://raw.githubusercontent.com/Orz-3/mini/master/Color/kuaishou.png" + ] + }, { - "id": "jddj", - "name": "京东到家", - "keys": ["sy_cookie_dj"], - "author": "@sunert", - "repo": "https://gitee.com/Sunert/Scripts/blob/master/Task/jddj.js", - "icons": ["https://raw.githubusercontent.com/Orz-3/mini/master/jddj.png", "https://raw.githubusercontent.com/Orz-3/task/master/jddj.png"], - "script": "https://raw.githubusercontent.com/Sunert/Scripts/master/Task/jddj.js" - }, + "author": "@sunert", + "keys": [ + "sy_signurl_snews", + "sy_info_snews", + "sy_ck_snews", + "sy_infoheader_snews" + ], + "repo": "https://github.com/Sunert/Scripts/blob/master/Task/sinanews.js", + "id": "sinanews", + "script": "https://raw.githubusercontent.com/Sunert/Scripts/master/Task/sinanews.js", + "name": "新浪新闻", + "icons": [ + "https://raw.githubusercontent.com/Orz-3/mini/master/sinanews.png", + "https://raw.githubusercontent.com/Orz-3/mini/master/Color/sinanews.png" + ] + }, { - "id": "TVlist", - "name": "电视预告", - "keys": [], - "settings": [{ - "id": "c", - "name": "电视台", - "val": "cctv8", - "type": "text", - "desc": "请填写小写英文台标,示例: 北京: btv1 | 湖南: hunan | 浙江: zhejiang 河南: henan| 江苏: jiangsu|广东: guangdong 更多电视台请参加电视家网络列表" }], - "author": "@sunert", - "repo": "https://gitee.com/Sunert/Scripts/blob/master/Task/tvpreview.js", - "icons": ["https://raw.githubusercontent.com/Sunert/Quantumult-X/master/Rules/Images/ICON/tvpreview.png", "https://raw.githubusercontent.com/Sunert/Quantumult-X/master/Rules/Images/ICON/tvpreview.png"], - "script": "https://gitee.com/Sunert/Scripts/raw/master/Task/tvpreview.js" - }, + "author": "@sunert", + "keys": [ + "china_telecom_authToken_10000", + "china_telecom_cookie" + ], + "repo": "https://github.com/Sunert/Scripts/blob/master/Task/telecomInfinity.js", + "id": "chinatelecomEnquiry", + "script": "https://raw.githubusercontent.com/Sunert/Scripts/master/Task/telecomInfinity.js", + "settings": [ + { + "id": "Mon", + "val": "2020-08", + "name": "查询月份", + "type": "month", + "desc": "填入账单月份,可查最近六个月,本月账单下月可查" + } + ], + "name": "天翼电信套餐查询", + "icons": [ + "https://raw.githubusercontent.com/Orz-3/mini/master/telecominfinty.png", + "https://raw.githubusercontent.com/Orz-3/mini/master/Color/telecominfinty.png" + ] + }, { - "id": "mydigit", - "name": "数码之家", - "keys": ["sign_mydigit"], - "author": "@sunert", - "repo": "https://gitee.com/Sunert/Scripts/blob/master/Task/mydigit.js", - "icons": ["https://raw.githubusercontent.com/Orz-3/mini/master/mydigit.png", "https://raw.githubusercontent.com/Orz-3/task/master/mydigit.png"], - "script": "https://gitee.com/Sunert/Scripts/raw/master/Task/mydigit.js" - }, + "author": "@sunert", + "keys": [ + "sy_cookie_dj" + ], + "repo": "https://github.com/Sunert/Scripts/blob/master/Task/jddj.js", + "id": "jddj", + "script": "https://raw.githubusercontent.com/Sunert/Scripts/master/Task/jddj.js", + "name": "京东到家", + "icons": [ + "https://raw.githubusercontent.com/Orz-3/mini/master/jddj.png", + "https://raw.githubusercontent.com/Orz-3/mini/master/Color/jddj.png" + ] + }, { - "id": "txnews", - "name": "腾讯新闻", - "keys": ["sy_signurl_txnews", "sy_cookie_txnews","video_txnews"], - "author": "@sunert", + "author": "@sunert", + "keys": [ + "c" + ], + "repo": "https://github.com/Sunert/Scripts/blob/master/Task/tvpreview.js", + "id": "TVlist", + "script": "https://raw.githubusercontent.com/Sunert/Scripts/master/Task/tvpreview.js", "settings": [ { - "id": "notifynum", - "name": "通知频率", - "val": "", - "type": "number", - "placeholder": "默认50 (点击以展开说明)", + "id": "c", + "val": "cctv8", + "name": "电视台", + "type": "text", + "desc": "请填写小写英文台标,示例: 北京: btv1 | 湖南: hunan | 浙江: zhejiang 河南: henan| 江苏: jiangsu|广东: guangdong 更多电视台请参加电视家网络列表" + } + ], + "name": "电视预告", + "icons": [ + "https://github.com/Sunert/Profiles/raw/master/QuantumultX/Rules/Images/icon/tvpreview_mini.png", + "https://github.com/Sunert/Profiles/raw/master/QuantumultX/Rules/Images/icon/tvpreview.png" + ] + }, + { + "author": "@sunert", + "keys": [ + "city", + "citynum", + "cut", + "day_desc", + "hour_desc", + "index_desc" + ], + "repo": "https://github.com/Sunert/Scripts/blob/master/Task/moji.js", + "id": "moji", + "script": "https://raw.githubusercontent.com/Sunert/Scripts/master/Task/moji.js", + "settings": [ + { + "id": "city", + "val": "北京", + "name": "城市", + "type": "text", + "desc": "请填写中文地区" + }, + { + "id": "citynum", + "placeholder": "默认1 (点击以展开说明)", + "val": "", + "name": "城市序号", + "type": "number", + "desc": "选择地区,请填写日志内冒号前的数字序号" + }, + { + "id": "cut", + "val": false, + "name": "精简日志模式", + "type": "boolean", + "desc": "显示详情描述,默认关闭日志" + }, + { + "id": "day_desc", + "val": true, + "name": "每周天气", + "type": "boolean", + "desc": "每周天气接口,可显示6天天气情况" + }, + { + "id": "hour_desc", + "val": false, + "name": "小时天气", + "type": "boolean", + "desc": "未来6小时天气情况" + }, + { + "id": "forty_desc", + "val": false, + "name": "40天预告", + "type": "boolean", + "desc": "未来40天天气预告" + }, + { + "id": "index_desc", + "val": true, + "name": "生活指数", + "type": "boolean", + "desc": "可显示生活指数情况" + } + ], + "name": "墨迹天气", + "icons": [ + "https://github.com/Sunert/Profiles/raw/master/QuantumultX/Rules/Images/icon/moji_mini.png", + "https://github.com/Sunert/Profiles/raw/master/QuantumultX/Rules/Images/icon/moji.png" + ] + }, + { + "author": "@sunert", + "keys": [ + "jukan_body", + "jukan_name" + ], + "repo": "https://github.com/Sunert/Scripts/blob/master/Task/jukan.js", + "id": "jukan", + "script": "https://raw.githubusercontent.com/Sunert/Scripts/master/Task/jukan.js", + "settings": [ + { + "id": "jukan_out", + "val": false, + "name": "自动提现", + "type": "boolean", + "desc": "自动提现开关,请填入提现金额及微信绑定实名,默认关闭" + }, + { + "id": "jukan_cash", + "val": "", + "name": "提现金额", + "type": "radios", + "items": [ + { + "key": "3", + "label": "3元(邀请专享)" + }, + { + "key": "10", + "label": "10元(阅读/邀请)" + }, + { + "key": "30", + "label": "30元(无条件)" + }, + { + "key": "50", + "label": "50元(无条件)" + }, + { + "key": "100", + "label": "100元(无条件)" + } + ] + }, + { + "id": "jukan_name", + "placeholder": "填入微信真实姓名", + "val": "", + "name": "微信真实姓名", + "type": "text" + } + ], + "name": "聚看点", + "icons": [ + "https://github.com/Sunert/Profiles/raw/master/QuantumultX/Rules/Images/icon/jukan_mini.png", + "https://github.com/Sunert/Profiles/raw/master/QuantumultX/Rules/Images/icon/jukan.png" + ] + }, + { + "author": "@sunert", + "keys": [ + "sign_mydigit" + ], + "repo": "https://github.com/Sunert/Scripts/blob/master/Task/mydigit.js", + "id": "mydigit", + "script": "https://raw.githubusercontent.com/Sunert/Scripts/master/Task/mydigit.js", + "name": "数码之家", + "icons": [ + "https://raw.githubusercontent.com/Orz-3/mini/master/mydigit.png", + "https://raw.githubusercontent.com/Orz-3/mini/master/Color/mydigit.png" + ] + }, + { + "author": "@sunert", + "keys": [ + "baidu_nick", + "chavy_cookie_tieba", + "CookieTB", + "cash_baidu" + ], + "repo": "https://github.com/Sunert/Scripts/blob/master/Task/baiduspeed.js", + "id": "baidu", + "script": "https://raw.githubusercontent.com/Sunert/Scripts/master/Task/baiduspeed.js", + "settings": [ + { + "items": [ + { + "key": "5", + "label": "5元" + }, + { + "key": "30", + "label": "30元" + }, + { + "key": "50", + "label": "50元" + }, + { + "key": "100", + "label": "100元" + } + ], + "id": "cash_baidu", + "val": "30", + "name": "提现金额", + "type": "radios", + "desc": "自动提现金额" + }, + { + "id": "task_baidu", + "val": true, + "name": "任务开关", + "type": "boolean", + "desc": "除提现和兑换金币外开关,默认开启所有任务" + } + ], + "name": "百度极速任务", + "icons": [ + "https://raw.githubusercontent.com/Sunert/Profiles/master/QuantumultX/Rules/Images/icon/baiduspeed_mini.png", + "https://raw.githubusercontent.com/Sunert/Profiles/master/QuantumultX/Rules/Images/icon/baiduspeed.png" + ] + }, + { + "author": "@sunert", + "keys": [ + "sy_signurl_txnews", + "sy_cookie_txnews", + "video_txnews", + "txnews_id" + ], + "repo": "https://github.com/Sunert/Scripts/blob/master/Task/txnews.js", + "id": "txnews", + "script": "https://raw.githubusercontent.com/Sunert/Scripts/master/Task/txnews.js", + "settings": [ + { + "id": "notifynum", + "placeholder": "默认50 (点击以展开说明)", + "val": "", + "name": "通知频率", + "type": "number", "desc": "阅读篇数间隔通知开为1,常关为0(默认50篇)" - }, + }, { - "id": "delay", - "name": "延迟时间(毫秒)", - "val": "", - "type": "number", - "placeholder": "默认200 (点击以展开说明)", + "id": "delay", + "placeholder": "默认200 (点击以展开说明)", + "val": "", + "name": "延迟时间(毫秒)", + "type": "number", "desc": "接口延迟时间" - } - ], - "repo": "https://gitee.com/Sunert/Scripts/blob/master/Task/txnews.js", - "icons": ["https://raw.githubusercontent.com/Orz-3/mini/master/txnews.png", "https://raw.githubusercontent.com/Orz-3/task/master/txnews.png"], - "script": "https://gitee.com/Sunert/Scripts/raw/master/Task/txnews.js" - }, - { - "id": "jingxi", - "name": "京喜", - "keys": ["CookieJD", "CookieJD2"], - "author": "@sunert", - "repo": "https://gitee.com/Sunert/Scripts/blob/master/Task/jingxi.js", - "icons": ["https://raw.githubusercontent.com/Orz-3/mini/master/jingxi.png", "https://raw.githubusercontent.com/Orz-3/task/master/jingxi.png"], - "script": "https://gitee.com/Sunert/Scripts/raw/master/Task/jingxi.js" - }, + } + ], + "name": "腾讯新闻", + "icons": [ + "https://raw.githubusercontent.com/Orz-3/mini/master/txnews.png", + "https://raw.githubusercontent.com/Orz-3/mini/master/Color/txnews.png" + ] + }, { - "id": "translate", - "name": "谷歌翻译", - "keys": [], - "settings": [{ - "id": "word", - "name": "原文", - "val": "Hello World", - "type": "textarea", - "placeholder": "Hello World", - "desc": "兼容中英文短语翻译,填入原文后手动运行" }], - "author": "@sunert", - "repo": "https://gitee.com/Sunert/Scripts/blob/master/Task/tvpreview.js", - "icons": ["https://raw.githubusercontent.com/Orz-3/mini/master/translate.png", "https://raw.githubusercontent.com/Orz-3/task/master/translate.png"], - "script": "https://gitee.com/Sunert/Scripts/raw/master/Task/translate.js" - }, + "author": "@sunert", + "keys": [ ], + "repo": "https://github.com/Sunert/Scripts/blob/master/Task/tvpreview.js", + "id": "translate", + "script": "https://raw.githubusercontent.com/Sunert/Scripts/master/Task/translate.js", + "settings": [ + { + "id": "word", + "placeholder": "Hello World", + "val": "Hello World", + "name": "原文", + "type": "textarea", + "desc": "兼容中英文短语翻译,填入原文后手动运行" + } + ], + "name": "谷歌翻译", + "icons": [ + "https://raw.githubusercontent.com/Orz-3/mini/master/translate.png", + "https://raw.githubusercontent.com/Orz-3/mini/master/Color/translate.png" + ] + }, { - "id": "exchange rate", - "name": "汇率换算", - "keys": [], + "author": "@sunert", + "keys": [ ], + "repo": "https://github.com/Sunert/Scripts/blob/master/Task/exchangeRate.js", + "id": "exchange rate", + "script": "https://raw.githubusercontent.com/Sunert/Scripts/master/Task/exchangeRate.js", "settings": [ - { - "id": "froma", - "name": "使用币", - "val": "人民币", - "type": "text", - "desc": "填写中文币种,注意澳门元为澳门帕塔卡,香港元为港币,台湾为新台币" - }, - { - "id": "toex", - "name": "兑换币", - "val": "港币", - "type": "text", - "desc": "填写中文币种,注意澳门元为澳门帕塔卡,香港元为港币,台湾为新台币" - }, - { - "id": "numex", - "name": "兑换金额", - "val": "10", - "type": "number", - "desc": "填写数字" - } - ], - "author": "@sunert", - "repo": "https://gitee.com/Sunert/Scripts/blob/master/Task/exchangeRate.js", - "icons": ["https://raw.githubusercontent.com/Orz-3/mini/master/exchangerate.png", "https://raw.githubusercontent.com/Orz-3/task/master/exchangerate.png"], - "script": "https://gitee.com/Sunert/Scripts/raw/master/Task/exchangeRate.js" - }, + { + "id": "froma", + "val": "人民币", + "name": "使用币", + "type": "text", + "desc": "填写中文币种,注意澳门元为澳门帕塔卡,香港元为港币,台湾为新台币" + }, + { + "id": "toex", + "val": "港币", + "name": "兑换币", + "type": "text", + "desc": "填写中文币种,注意澳门元为澳门帕塔卡,香港元为港币,台湾为新台币" + }, + { + "id": "numex", + "val": "10", + "name": "兑换金额", + "type": "number", + "desc": "填写数字" + } + ], + "name": "汇率换算", + "icons": [ + "https://raw.githubusercontent.com/Orz-3/mini/master/exchangerate.png", + "https://raw.githubusercontent.com/Orz-3/mini/master/Color/exchangerate.png" + ] + }, { - "id": "trainquery", - "name": "列车时刻", - "keys": [], + "author": "@sunert", + "keys": [ ], + "repo": "https://github.com/Sunert/Scripts/blob/master/Task/trainquery.js", + "id": "trainquery", + "script": "https://raw.githubusercontent.com/Sunert/Scripts/master/Task/trainquery.js", "settings": [ - { - "id": "people", - "name": "乘客类型", - "val": "ADULT", - "type": "radios", - "desc": "成人/学生", - "items": [ + { + "items": [ { - "key": "ADULT", + "key": "ADULT", "label": "成人" - }, + }, { - "key": "0X00", + "key": "0X00", "label": "学生" - }] - }, - { + } + ], + "id": "people", + "val": "ADULT", + "name": "乘客类型", + "type": "radios", + "desc": "成人/学生" + }, + { "id": "left", - "name": "出发站点", "val": "北京", + "name": "出发站点", "type": "text", - "desc": "填入中文站点" - }, - { + "desc": "填入中文站点" + }, + { "id": "end", - "name": "目的地", "val": "上海", + "name": "目的地", "type": "text", - "desc": "填入中文站点" - }, - { + "desc": "填入中文站点" + }, + { "id": "leavedate", - "name": "出发时间", "val": "2020-08-15", + "name": "出发时间", "type": "date", - "desc": "填入出发日期,请按照格式填写" - }, - { + "desc": "填入出发日期,请按照格式填写" + }, + { "id": "setrain", - "name": "列车车次", "val": "G5", + "name": "列车车次", "type": "text", - "desc": "填入列车车次或者列车序号,列车序号请查看日志详情" - } - ], - "author": "@sunert", - "repo": "https://gitee.com/Sunert/Scripts/blob/master/Task/trainquery.js", - "icons": ["https://raw.githubusercontent.com/Orz-3/mini/master/12306.png", "https://raw.githubusercontent.com/Orz-3/task/master/12306.png"], - "script": "https://gitee.com/Sunert/Scripts/raw/master/Task/trainquery.js" + "desc": "填入列车车次或者列车序号,列车序号请查看日志详情" + } + ], + "name": "列车时刻", + "icons": [ + "https://raw.githubusercontent.com/Orz-3/mini/master/12306.png", + "https://raw.githubusercontent.com/Orz-3/mini/master/Color/12306.png" + ] } ] -} +} \ No newline at end of file diff --git a/Task/trainquery.js b/Task/trainquery.js index 5116e98573..10dbbf6de0 100644 --- a/Task/trainquery.js +++ b/Task/trainquery.js @@ -5,11 +5,11 @@ 2.K值为列车车次所对应的序号或者车次,请不要填错,详情请看日志 3.部分列车无法查到列车时刻信息,部分列车总计时间有误,以时刻表为准,部分座席可能无票价,第一次运行会报错,请重新运行 4.提供所有席别余票信息,测试阶段,仅供参考 -5.借鉴sazs34大佬的smart脚本 -更新日志: -7月28日: -取消手动座席选择,增加硬卧,软卧,商务座等所有票价信息,优化通知; + 支持boxjs远程自定义配置,增加可自定义车次,车次序号设置过大时可显示经过车次,可根据车次序号进行设置,由于苹果限制,车次可能显示不全 + +如果设置出行日期若已过,则自动修改为明天,可在Boxjs内手动修改出行日期 + 增加点击通知链接跳转详情页 ~~~~~~~~~~~~~~~~ QX 1.0.6+ : @@ -31,34 +31,31 @@ cron "04 00 * * *" script-path=https://raw.githubusercontent.com/Sunert/Scripts/ */ +const $ = new Env('列车时刻查询'); -const leftstat ='北京' //出发地 - - tostat = '上海' //目的地 - - peo = 'ADULT' //乘客类型,'ADULT'是成人,'0X00'是学生 - - lefdate = '2020-08-15' //出发日期 + //出发地 +let leftstation = $.getdata('left')||'北京' - settrain = '1' //车次序号或者列车车次!! +// 目的地 +let tostation = $.getdata('end')||'上海' -const $ = new Env('列车时刻查询') +//乘客类型,'ADULT'是成人,'0X00'是学生 +let purpose = $.getdata('people')||peo - leftstation = $.getdata('left')||leftstat +//出发日期 +let leftdate = $.getdata('leavedate') - tostation = $.getdata('end')||tostat - - purpose = $.getdata('people')||peo - - leftdate = $.getdata('leavedate')||lefdate - -let K = $.getdata('setrain')||settrain +//车次序号或者列车车次!! +let K = $.getdata('setrain')||"1" !(async () => { - await namecheck() - await trainscheck() - await prize() - await traintime() + await namecheck(); + await timecheck(); + await $.wait(800) + await trainscheck(); + await $.wait(800) + await prize(); + //await traintime() })() .catch((e) => $.logErr(e)) .finally(() => $.done()) @@ -66,163 +63,180 @@ let K = $.getdata('setrain')||settrain //站点编码 function namecheck() { - return new Promise((resolve, reject) =>{ -const stationnocheck = { - url: `https://kyfw.12306.cn/otn/resources/js/framework/station_name.js`, - method: 'GET', -}; - $.get(stationnocheck, (err, resp, data) => { - //console.log(response.statusCode + "\n\n" + data); - statno =data.split(`${leftstation}`)[1].split("|")[1] - tostat = data.split(`${tostation}`)[1].split("|")[1] - resolve() - }) - }) + return new Promise((resolve, reject) =>{ + const stationnocheck = { + url: `https://kyfw.12306.cn/otn/resources/js/framework/station_name.js`, + method: 'GET', + }; + $.get(stationnocheck, (err, resp, data) =>{ + //console.log(resp.statusCode + "\n\n" + data); + try { + statno = data.split(`${leftstation}`)[1].split("|")[1]; + tostat = data.split(`${tostation}`)[1].split("|")[1] + } catch(e) { + $.logErr(e, data); + } finally { + resolve() + } + }) + }) } -let nowDate = $.time('yyyy-MM-dd'); -if (nowDate > leftdate ){ - $.msg(`火车查询错误❌`,"日期错误,请检查后重试",'') +function timecheck() { + let nowDate = $.time('yyyy-MM-dd'); + if (nowDate > leftdate) { + lastday = $.time("yyyy-MM") + "-" + new Date($.time("yyyy"), $.time("MM"), 0).getDate(); + if (leftdate < lastday) { + leftdate = $.time("yyyy-MM") + "-" + `${parseInt($.time("dd")) + 1}`.padStart(2, "0") ; + $.log("设置出行日期已过,将自动把出行日期改为明天") + } + } } // 获取车次列表 function trainscheck() { - return new Promise((resolve, reject) =>{ - const myRequest = { - url: `https://kyfw.12306.cn/otn/leftTicket/query?leftTicketDTO.train_date=${leftdate}&leftTicketDTO.from_station=${statno}&leftTicketDTO.to_station=${tostat}&purpose_codes=${purpose}`, - method: 'GET', - headers: {'Cookie' : 'JSESSIONID=1B1CEADF1B9F831C25E71D7F2D996294'} -}; - $.get(myRequest, (err, resp, data) => { - //console.log('余票信息' + "\n\n" + data); - let ress = JSON.parse(data) -try { - let reg = /^[a-zA-Z][0-9]+$/ - for (i=0;iress.data.result.length){ - var trainlist = "" -for (y=0;y{ + const myRequest = { + url: `https://kyfw.12306.cn/otn/leftTicket/queryZ?leftTicketDTO.train_date=${leftdate}&leftTicketDTO.from_station=${statno}&leftTicketDTO.to_station=${tostat}&purpose_codes=${purpose}`, + headers:{ + Cookie: 'JSESSIONID=E3CCA5C6ECC49AFFE24D4FE48C8A8949;', + 'Referer': 'https://kyfw.12306.cn/otn/leftTicket/init' + } + }; + $.get(myRequest, (err, resp, data) =>{ + //console.log('余票信息' + "\n\n" + data); + try { + let ress = JSON.parse(data); + let reg = /^[a-zA-Z][0-9]+$/; + for (i = 0; i < ress.data.result.length; i++) { + yupiaoinfo = ress.data.result[i].split("|"); + train = yupiaoinfo[3]; + hours = yupiaoinfo[10].split(":")[0] + if(train&&hours!=99){ + starttime = yupiaoinfo[8], + arrivetime = yupiaoinfo[9], + total = yupiaoinfo[10].split(":")[0] + '小时' + yupiaoinfo[10].split(":")[1] + '分钟', + yingzuo = yupiaoinfo[29]?' 硬座:' + yupiaoinfo[29]:"", + yingwo = yupiaoinfo[28]?" 硬卧:" + yupiaoinfo[28]:"", + ruanwo = yupiaoinfo[23]? " 软卧:" + yupiaoinfo[23]:"", + yideng = yupiaoinfo[31]?' 一等座:' + yupiaoinfo[31]:"", + erdeng = yupiaoinfo[30]?' 二等座:' + yupiaoinfo[30]:"", + wuzuo = yupiaoinfo[26]? ' 无座:' + yupiaoinfo[26]:"" + } + trainlist = '[' + (i + 1) + '] 车次:' + train + " " + starttime + "--" + arrivetime + " 总计时间:" + total + ' ' + yideng + " "+ erdeng + " "+ yingwo + ruanwo +" "+yingzuo +" "+ wuzuo + '\n' + //trainno = ress.data.result[i].split("|")[2] + $.log(trainlist); + if (reg.test(K) && K == ress.data.result[i].split("|")[3]) { + K = i + 1 + } + }; + if (K <= ress.data.result.length) { + info = ress.data.result[K - 1].split("|"); + //console.log(info) + + traincode = info[3]; + //列车车次 + if( info.indexOf("列车停运")>-1){ + $.msg( $.name, traincode+"车次于"+leftdate+"已停运","请选择其他车次") + $done() + }; + if( info.indexOf("IS_TIME_NOT_BUY")>-1){ + $.log("您选的"+traincode+"车次出行日期不在购买时间段,请选择其他车次或者调整出行日期") + } + trainno = info[2], + //列车编码 + fromstationno = info[16], + //发车站序号 + tostationno = info[17], + //目的地序号 + fromstation = info[4], + //始发站编码 + endstation = info[5], + //终点站编码 + leftstationcode = info[6], + //出发站编码 + tostationcode = info[7], + //目的地编码 + seattypes = info[35], + //座席代码 + totaltime = info[10].split(":")[0] + '小时' + info[10].split(":")[1] + '分钟'; + //运行时间 + } else if (!reg.test(K) && K > ress.data.result.length) { + var trainlist = ""; + for (y = 0; y < ress.data.result.length; y++) { + trainlist += (y + 1) + '. ' + ress.data.result[y].split("|")[3] + " " + ress.data.result[y].split("|")[8] + "-" + ress.data.result[y].split("|")[9] + " 历时" + ress.data.result[y].split("|")[10].split(":")[0] + '时' + ress.data.result[y].split("|")[10].split(":")[1] + '分\n' + } + $.msg(`火车查询错误❌`, "共" + ress.data.result.length + "辆列车经过,请检查后重试", trainlist); + return + } + } catch(e) { + $.msg(`火车查询错误❌`, "无此方向列车经过,请检查后重试", e); + return + } finally { + resolve() + } + }) }) } - function prize() { - return new Promise((resolve, reject) =>{ - var timestamp=$.startTime; - const prizeurl = { - url: `https://kyfw.12306.cn/otn/leftTicket/queryTicketPrice?train_no=${trainno}&from_station_no=${fromstationno}&to_station_no=${tostationno}&seat_types=${seattypes}&train_date=${leftdate}`, - method: 'GET', - headers : {'Accept-Encoding' : `gzip, deflate, br`, -'Connection' : `keep-alive`, -'Accept' : `text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8`, -'Host' : `kyfw.12306.cn`, -'Cookie' : `_uab_collina=159587465195914267490366; JSESSIONID=2D2C3ED0892CE56ADB0576B030CC1344; _jc_save_fromDate=${leftdate}; _jc_save_fromStation=${leftstation}%2C${leftstationcode}; _jc_save_toDate=${leftdate}; _jc_save_toStation=${tostation}%2${tostationcode}; _jc_save_wfdc_flag=dc; BIGipServerotn=250610186.64545.0000; route=9036359bb8a8a461c164a04f8f50b252; RAIL_EXPIRATION=${timestamp}`, -'User-Agent' : `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/604.3.5 (KHTML, like Gecko) Version/13.0 Safari/604.1`, -'Accept-Language' : `zh-cn` } -} - $.get(prizeurl, (err, resp, data) => { - //console.log('票价信息: 响应码: ' +resp.statusCode+" \n"+ data+'\n'); - if ( data == -1){ - $.msg('列车查询失败‼️', '该'+traincode+'次列车车票暂停发售或者查询失败,请重试', err) - return + return new Promise((resolve, reject) =>{ + const prizeurl = { + url: `https://kyfw.12306.cn/otn/leftTicket/queryTicketPrice?train_no=${trainno}&from_station_no=${fromstationno}&to_station_no=${tostationno}&seat_types=${seattypes}&train_date=${leftdate}`, + headers:{ + Cookie: 'JSESSIONID=E3CCA5C6ECC49AFFE24D4FE48C8A8949;', + 'Referer': 'https://kyfw.12306.cn/otn/leftTicket/init' + } + }; + + $.get(prizeurl, async(err, resp, data) => { + console.log('票价信息: 响应码: ' +resp.statusCode+" \n"+ data+'\n'); + try{ + if (data == -1){ + $.msg('列车查询失败‼️', '该'+traincode+'次列车车票暂停发售或者查询失败,请重试', err); + return } - let result = JSON.parse(data) - if (result.data.M){ - setyideng += `(${result.data.M}) ` - } - if (result.data.O){ - seterdeng += `(${result.data.O}) ` - } - if (result.data.A3){ - setyingwo += `(${result.data.A3}) ` - } - if (result.data.F){ - setdongwo += `(${result.data.F}) ` - } - if (result.data.A1){ - setyingzuo += `(${result.data.A1}) ` - } - if (result.data.A2){ - setruanzuo += `(${result.data.A2}) ` - } - if (result.data.WZ){ - setwuzuo += `(${result.data.WZ}) ` - } - if (result.data.A9){ - setshangwu += `(${result.data.A9}) ` - } - if (result.data.AI){ - setruanwo += `(${result.data.AI}) ` - } - if (result.data.A4){ - setruanwo += `(${result.data.A4}) ` - } - if (result.data.A6){ - setruanwopro += `(${result.data.A6}) ` - } - if (result.data.AJ){ - setyingwo += `(${result.data.AJ}) ` - } - }) -resolve() + let obj = JSON.parse(data).data + var seatinfo = ""; + for ( arr in obj){ + if(obj[arr].indexOf("¥")>-1){ + seatinfo += mapSeat(arr)[0]+": "+(mapSeat(arr)[1]?mapSeat(arr)[1]:"")+"("+obj[arr]+") "; + } + if(seatinfo.split("¥").length%3==0){ + seatinfo += "\n" + } + } + await traintime(seatinfo) + } catch(e) { + $.logErr(e, data); + } finally { + resolve() + } + }) }) } -function traintime() { +function mapSeat(seat) { + const map = { + "M": ["一等座", info[31]], + "O": ["二等座", info[30]], + "A1": ["硬座", info[29]], + "A2": ["软座", info[24]], + "A3": ["硬卧", info[28]], + "AJ": ["二等卧", info[28]], + "A4": ["软卧", info[23]], + "AI": ["二等卧", info[23]], + "A6": ["豪华软卧", info[21]], + "A9": ["商务座", info[32]], + "P": ["特等座", info[32]], + "F": ["动卧", info[33]], + "WZ": ["无座", info[26]] + } + return map[seat] +} + + +function traintime(seatinfo) { return new Promise((resolve, reject) =>{ const myRequest = { url: `https://kyfw.12306.cn/otn/czxx/queryByTrainNo?train_no=${trainno}&from_station_telecode=${fromstation}&to_station_telecode=${endstation}&depart_date=${leftdate}`, @@ -230,7 +244,7 @@ function traintime() { } $.get(myRequest, (err, resp, data) => { var detail = "" - //console.log(response.statusCode + "\n\n" + data); + //console.log(resp.statusCode + "\n\n" + data); let result = JSON.parse(data) if (result.status == true) { const traincode = result.data.data[0].station_train_code @@ -240,47 +254,14 @@ const arrivetime = result.data.data[0].arrive_time startstation = result.data.data[0].start_station_name edstation = result.data.data[0].end_station_name -if (setyideng){ - detail += '一等座: '+setyideng - } -if (seterdeng){ - detail += ' 二等座: '+seterdeng - } -if (setshangwu){ - detail += '\n商务座: '+setshangwu - } -if (setyingzuo){ - detail += '硬座: '+setyingzuo - } -if (setruanzuo){ - detail += ' 软座: '+setruanzuo - } -if (setwuzuo){ - detail += ' 无座: '+setwuzuo - } -if (setruanwo){ - detail += '\n软卧: '+setruanwo - } -if (setyingwo){ - detail += ' 硬卧: '+setyingwo - } -if (setruanwopro){ - detail += ' 高级软卧: '+setruanwopro - } -if (setdongwo){ - detail += ' 动卧: '+setdongwo - } if (purpose=='0X00'){ - purpose = '学生票 ' + purpose = '学生票' } else { - purpose = '成人票 ' + purpose = '成人票' } - if(detail==""){ - detail += "该列车车票暂停发售或已停运,点击打开详情页查看" - } -else{ - detail +="\n"+leftstation+'到达目的地'+tostation+'历时'+totaltime+'\n'+arrivetime +'--'+starttime+ ' '+stationname +if(seatinfo){ + detail = seatinfo+"\n"+leftstation+'到达目的地'+tostation+'历时'+totaltime+'\n'+arrivetime +'--'+starttime+ ' '+stationname } for (i=1;i{s.call(this,t,(t,s,r)=>{t?i(t):e(s)})})}get(t){return this.send.call(this.env,t)}post(t){return this.send.call(this.env,t,"POST")}}return new class{constructor(t,e){this.name=t,this.http=new s(this),this.data=null,this.dataFile="box.dat",this.logs=[],this.isMute=!1,this.isNeedRewrite=!1,this.logSeparator="\n",this.startTime=(new Date).getTime(),Object.assign(this,e),this.log("",`\ud83d\udd14${this.name}, \u5f00\u59cb!`)}isNode(){return"undefined"!=typeof module&&!!module.exports}isQuanX(){return"undefined"!=typeof $task}isSurge(){return"undefined"!=typeof $httpClient&&"undefined"==typeof $loon}isLoon(){return"undefined"!=typeof $loon}toObj(t,e=null){try{return JSON.parse(t)}catch{return e}}toStr(t,e=null){try{return JSON.stringify(t)}catch{return e}}getjson(t,e){let s=e;const i=this.getdata(t);if(i)try{s=JSON.parse(this.getdata(t))}catch{}return s}setjson(t,e){try{return this.setdata(JSON.stringify(t),e)}catch{return!1}}getScript(t){return new Promise(e=>{this.get({url:t},(t,s,i)=>e(i))})}runScript(t,e){return new Promise(s=>{let i=this.getdata("@chavy_boxjs_userCfgs.httpapi");i=i?i.replace(/\n/g,"").trim():i;let r=this.getdata("@chavy_boxjs_userCfgs.httpapi_timeout");r=r?1*r:20,r=e&&e.timeout?e.timeout:r;const[o,h]=i.split("@"),a={url:`http://${h}/v1/scripting/evaluate`,body:{script_text:t,mock_type:"cron",timeout:r},headers:{"X-Key":o,Accept:"*/*"}};this.post(a,(t,e,i)=>s(i))}).catch(t=>this.logErr(t))}loaddata(){if(!this.isNode())return{};{this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(this.dataFile),e=this.path.resolve(process.cwd(),this.dataFile),s=this.fs.existsSync(t),i=!s&&this.fs.existsSync(e);if(!s&&!i)return{};{const i=s?t:e;try{return JSON.parse(this.fs.readFileSync(i))}catch(t){return{}}}}}writedata(){if(this.isNode()){this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(this.dataFile),e=this.path.resolve(process.cwd(),this.dataFile),s=this.fs.existsSync(t),i=!s&&this.fs.existsSync(e),r=JSON.stringify(this.data);s?this.fs.writeFileSync(t,r):i?this.fs.writeFileSync(e,r):this.fs.writeFileSync(t,r)}}lodash_get(t,e,s){const i=e.replace(/\[(\d+)\]/g,".$1").split(".");let r=t;for(const t of i)if(r=Object(r)[t],void 0===r)return s;return r}lodash_set(t,e,s){return Object(t)!==t?t:(Array.isArray(e)||(e=e.toString().match(/[^.[\]]+/g)||[]),e.slice(0,-1).reduce((t,s,i)=>Object(t[s])===t[s]?t[s]:t[s]=Math.abs(e[i+1])>>0==+e[i+1]?[]:{},t)[e[e.length-1]]=s,t)}getdata(t){let e=this.getval(t);if(/^@/.test(t)){const[,s,i]=/^@(.*?)\.(.*?)$/.exec(t),r=s?this.getval(s):"";if(r)try{const t=JSON.parse(r);e=t?this.lodash_get(t,i,""):e}catch(t){e=""}}return e}setdata(t,e){let s=!1;if(/^@/.test(e)){const[,i,r]=/^@(.*?)\.(.*?)$/.exec(e),o=this.getval(i),h=i?"null"===o?null:o||"{}":"{}";try{const e=JSON.parse(h);this.lodash_set(e,r,t),s=this.setval(JSON.stringify(e),i)}catch(e){const o={};this.lodash_set(o,r,t),s=this.setval(JSON.stringify(o),i)}}else s=this.setval(t,e);return s}getval(t){return this.isSurge()||this.isLoon()?$persistentStore.read(t):this.isQuanX()?$prefs.valueForKey(t):this.isNode()?(this.data=this.loaddata(),this.data[t]):this.data&&this.data[t]||null}setval(t,e){return this.isSurge()||this.isLoon()?$persistentStore.write(t,e):this.isQuanX()?$prefs.setValueForKey(t,e):this.isNode()?(this.data=this.loaddata(),this.data[e]=t,this.writedata(),!0):this.data&&this.data[e]||null}initGotEnv(t){this.got=this.got?this.got:require("got"),this.cktough=this.cktough?this.cktough:require("tough-cookie"),this.ckjar=this.ckjar?this.ckjar:new this.cktough.CookieJar,t&&(t.headers=t.headers?t.headers:{},void 0===t.headers.Cookie&&void 0===t.cookieJar&&(t.cookieJar=this.ckjar))}get(t,e=(()=>{})){t.headers&&(delete t.headers["Content-Type"],delete t.headers["Content-Length"]),this.isSurge()||this.isLoon()?(this.isSurge()&&this.isNeedRewrite&&(t.headers=t.headers||{},Object.assign(t.headers,{"X-Surge-Skip-Scripting":!1})),$httpClient.get(t,(t,s,i)=>{!t&&s&&(s.body=i,s.statusCode=s.status),e(t,s,i)})):this.isQuanX()?(this.isNeedRewrite&&(t.opts=t.opts||{},Object.assign(t.opts,{hints:!1})),$task.fetch(t).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>e(t))):this.isNode()&&(this.initGotEnv(t),this.got(t).on("redirect",(t,e)=>{try{if(t.headers["set-cookie"]){const s=t.headers["set-cookie"].map(this.cktough.Cookie.parse).toString();this.ckjar.setCookieSync(s,null),e.cookieJar=this.ckjar}}catch(t){this.logErr(t)}}).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>{const{message:s,response:i}=t;e(s,i,i&&i.body)}))}post(t,e=(()=>{})){if(t.body&&t.headers&&!t.headers["Content-Type"]&&(t.headers["Content-Type"]="application/x-www-form-urlencoded"),t.headers&&delete t.headers["Content-Length"],this.isSurge()||this.isLoon())this.isSurge()&&this.isNeedRewrite&&(t.headers=t.headers||{},Object.assign(t.headers,{"X-Surge-Skip-Scripting":!1})),$httpClient.post(t,(t,s,i)=>{!t&&s&&(s.body=i,s.statusCode=s.status),e(t,s,i)});else if(this.isQuanX())t.method="POST",this.isNeedRewrite&&(t.opts=t.opts||{},Object.assign(t.opts,{hints:!1})),$task.fetch(t).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>e(t));else if(this.isNode()){this.initGotEnv(t);const{url:s,...i}=t;this.got.post(s,i).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>{const{message:s,response:i}=t;e(s,i,i&&i.body)})}}time(t){let e={"M+":(new Date).getMonth()+1,"d+":(new Date).getDate(),"H+":(new Date).getHours(),"m+":(new Date).getMinutes(),"s+":(new Date).getSeconds(),"q+":Math.floor(((new Date).getMonth()+3)/3),S:(new Date).getMilliseconds()};/(y+)/.test(t)&&(t=t.replace(RegExp.$1,((new Date).getFullYear()+"").substr(4-RegExp.$1.length)));for(let s in e)new RegExp("("+s+")").test(t)&&(t=t.replace(RegExp.$1,1==RegExp.$1.length?e[s]:("00"+e[s]).substr((""+e[s]).length)));return t}msg(e=t,s="",i="",r){const o=t=>{if(!t)return t;if("string"==typeof t)return this.isLoon()?t:this.isQuanX()?{"open-url":t}:this.isSurge()?{url:t}:void 0;if("object"==typeof t){if(this.isLoon()){let e=t.openUrl||t.url||t["open-url"],s=t.mediaUrl||t["media-url"];return{openUrl:e,mediaUrl:s}}if(this.isQuanX()){let e=t["open-url"]||t.url||t.openUrl,s=t["media-url"]||t.mediaUrl;return{"open-url":e,"media-url":s}}if(this.isSurge()){let e=t.url||t.openUrl||t["open-url"];return{url:e}}}};this.isMute||(this.isSurge()||this.isLoon()?$notification.post(e,s,i,o(r)):this.isQuanX()&&$notify(e,s,i,o(r)));let h=["","==============\ud83d\udce3\u7cfb\u7edf\u901a\u77e5\ud83d\udce3=============="];h.push(e),s&&h.push(s),i&&h.push(i),console.log(h.join("\n")),this.logs=this.logs.concat(h)}log(...t){t.length>0&&(this.logs=[...this.logs,...t]),console.log(t.join(this.logSeparator))}logErr(t,e){const s=!this.isSurge()&&!this.isQuanX()&&!this.isLoon();s?this.log("",`\u2757\ufe0f${this.name}, \u9519\u8bef!`,t.stack):this.log("",`\u2757\ufe0f${this.name}, \u9519\u8bef!`,t)}wait(t){return new Promise(e=>setTimeout(e,t))}done(t={}){const e=(new Date).getTime(),s=(e-this.startTime)/1e3;this.log("",`\ud83d\udd14${this.name}, \u7ed3\u675f! \ud83d\udd5b ${s} \u79d2`),this.log(),(this.isSurge()||this.isQuanX()||this.isLoon())&&$done(t)}}(t,e)} \ No newline at end of file +function Env(t,e){class s{constructor(t){this.env=t}send(t,e="GET"){t="string"==typeof t?{url:t}:t;let s=this.get;return"POST"===e&&(s=this.post),new Promise((e,i)=>{s.call(this,t,(t,s,r)=>{t?i(t):e(s)})})}get(t){return this.send.call(this.env,t)}post(t){return this.send.call(this.env,t,"POST")}}return new class{constructor(t,e){this.name=t,this.http=new s(this),this.data=null,this.dataFile="box.dat",this.logs=[],this.isMute=!1,this.isNeedRewrite=!1,this.logSeparator="\n",this.startTime=(new Date).getTime(),Object.assign(this,e),this.log("",`\ud83d\udd14${this.name}, \u5f00\u59cb!`)}isNode(){return"undefined"!=typeof module&&!!module.exports}isQuanX(){return"undefined"!=typeof $task}isSurge(){return"undefined"!=typeof $httpClient&&"undefined"==typeof $loon}isLoon(){return"undefined"!=typeof $loon}toObj(t,e=null){try{return JSON.parse(t)}catch{return e}}toStr(t,e=null){try{return JSON.stringify(t)}catch{return e}}getjson(t,e){let s=e;const i=this.getdata(t);if(i)try{s=JSON.parse(this.getdata(t))}catch{}return s}setjson(t,e){try{return this.setdata(JSON.stringify(t),e)}catch{return!1}}getScript(t){return new Promise(e=>{this.get({url:t},(t,s,i)=>e(i))})}runScript(t,e){return new Promise(s=>{let i=this.getdata("@chavy_boxjs_userCfgs.httpapi");i=i?i.replace(/\n/g,"").trim():i;let r=this.getdata("@chavy_boxjs_userCfgs.httpapi_timeout");r=r?1*r:20,r=e&&e.timeout?e.timeout:r;const[o,h]=i.split("@"),a={url:`http://${h}/v1/scripting/evaluate`,body:{script_text:t,mock_type:"cron",timeout:r},headers:{"X-Key":o,Accept:"*/*"}};this.post(a,(t,e,i)=>s(i))}).catch(t=>this.logErr(t))}loaddata(){if(!this.isNode())return{};{this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(this.dataFile),e=this.path.resolve(process.cwd(),this.dataFile),s=this.fs.existsSync(t),i=!s&&this.fs.existsSync(e);if(!s&&!i)return{};{const i=s?t:e;try{return JSON.parse(this.fs.readFileSync(i))}catch(t){return{}}}}}writedata(){if(this.isNode()){this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(this.dataFile),e=this.path.resolve(process.cwd(),this.dataFile),s=this.fs.existsSync(t),i=!s&&this.fs.existsSync(e),r=JSON.stringify(this.data);s?this.fs.writeFileSync(t,r):i?this.fs.writeFileSync(e,r):this.fs.writeFileSync(t,r)}}lodash_get(t,e,s){const i=e.replace(/\[(\d+)\]/g,".$1").split(".");let r=t;for(const t of i)if(r=Object(r)[t],void 0===r)return s;return r}lodash_set(t,e,s){return Object(t)!==t?t:(Array.isArray(e)||(e=e.toString().match(/[^.[\]]+/g)||[]),e.slice(0,-1).reduce((t,s,i)=>Object(t[s])===t[s]?t[s]:t[s]=Math.abs(e[i+1])>>0==+e[i+1]?[]:{},t)[e[e.length-1]]=s,t)}getdata(t){let e=this.getval(t);if(/^@/.test(t)){const[,s,i]=/^@(.*?)\.(.*?)$/.exec(t),r=s?this.getval(s):"";if(r)try{const t=JSON.parse(r);e=t?this.lodash_get(t,i,""):e}catch(t){e=""}}return e}setdata(t,e){let s=!1;if(/^@/.test(e)){const[,i,r]=/^@(.*?)\.(.*?)$/.exec(e),o=this.getval(i),h=i?"null"===o?null:o||"{}":"{}";try{const e=JSON.parse(h);this.lodash_set(e,r,t),s=this.setval(JSON.stringify(e),i)}catch(e){const o={};this.lodash_set(o,r,t),s=this.setval(JSON.stringify(o),i)}}else s=this.setval(t,e);return s}getval(t){return this.isSurge()||this.isLoon()?$persistentStore.read(t):this.isQuanX()?$prefs.valueForKey(t):this.isNode()?(this.data=this.loaddata(),this.data[t]):this.data&&this.data[t]||null}setval(t,e){return this.isSurge()||this.isLoon()?$persistentStore.write(t,e):this.isQuanX()?$prefs.setValueForKey(t,e):this.isNode()?(this.data=this.loaddata(),this.data[e]=t,this.writedata(),!0):this.data&&this.data[e]||null}initGotEnv(t){this.got=this.got?this.got:require("got"),this.cktough=this.cktough?this.cktough:require("tough-cookie"),this.ckjar=this.ckjar?this.ckjar:new this.cktough.CookieJar,t&&(t.headers=t.headers?t.headers:{},void 0===t.headers.Cookie&&void 0===t.cookieJar&&(t.cookieJar=this.ckjar))}get(t,e=(()=>{})){t.headers&&(delete t.headers["Content-Type"],delete t.headers["Content-Length"]),this.isSurge()||this.isLoon()?(this.isSurge()&&this.isNeedRewrite&&(t.headers=t.headers||{},Object.assign(t.headers,{"X-Surge-Skip-Scripting":!1})),$httpClient.get(t,(t,s,i)=>{!t&&s&&(s.body=i,s.statusCode=s.status),e(t,s,i)})):this.isQuanX()?(this.isNeedRewrite&&(t.opts=t.opts||{},Object.assign(t.opts,{hints:!1})),$task.fetch(t).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>e(t))):this.isNode()&&(this.initGotEnv(t),this.got(t).on("redirect",(t,e)=>{try{if(t.headers["set-cookie"]){const s=t.headers["set-cookie"].map(this.cktough.Cookie.parse).toString();this.ckjar.setCookieSync(s,null),e.cookieJar=this.ckjar}}catch(t){this.logErr(t)}}).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>{const{message:s,response:i}=t;e(s,i,i&&i.body)}))}post(t,e=(()=>{})){if(t.body&&t.headers&&!t.headers["Content-Type"]&&(t.headers["Content-Type"]="application/x-www-form-urlencoded"),t.headers&&delete t.headers["Content-Length"],this.isSurge()||this.isLoon())this.isSurge()&&this.isNeedRewrite&&(t.headers=t.headers||{},Object.assign(t.headers,{"X-Surge-Skip-Scripting":!1})),$httpClient.post(t,(t,s,i)=>{!t&&s&&(s.body=i,s.statusCode=s.status),e(t,s,i)});else if(this.isQuanX())t.method="POST",this.isNeedRewrite&&(t.opts=t.opts||{},Object.assign(t.opts,{hints:!1})),$task.fetch(t).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>e(t));else if(this.isNode()){this.initGotEnv(t);const{url:s,...i}=t;this.got.post(s,i).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>{const{message:s,response:i}=t;e(s,i,i&&i.body)})}}time(t){let e={"M+":(new Date).getMonth()+1,"d+":(new Date).getDate(),"H+":(new Date).getHours(),"m+":(new Date).getMinutes(),"s+":(new Date).getSeconds(),"q+":Math.floor(((new Date).getMonth()+3)/3),S:(new Date).getMilliseconds()};/(y+)/.test(t)&&(t=t.replace(RegExp.$1,((new Date).getFullYear()+"").substr(4-RegExp.$1.length)));for(let s in e)new RegExp("("+s+")").test(t)&&(t=t.replace(RegExp.$1,1==RegExp.$1.length?e[s]:("00"+e[s]).substr((""+e[s]).length)));return t}msg(e=t,s="",i="",r){const o=t=>{if(!t)return t;if("string"==typeof t)return this.isLoon()?t:this.isQuanX()?{"open-url":t}:this.isSurge()?{url:t}:void 0;if("object"==typeof t){if(this.isLoon()){let e=t.openUrl||t.url||t["open-url"],s=t.mediaUrl||t["media-url"];return{openUrl:e,mediaUrl:s}}if(this.isQuanX()){let e=t["open-url"]||t.url||t.openUrl,s=t["media-url"]||t.mediaUrl;return{"open-url":e,"media-url":s}}if(this.isSurge()){let e=t.url||t.openUrl||t["open-url"];return{url:e}}}};this.isMute||(this.isSurge()||this.isLoon()?$notification.post(e,s,i,o(r)):this.isQuanX()&&$notify(e,s,i,o(r)));let h=["","==============\ud83d\udce3\u7cfb\u7edf\u901a\u77e5\ud83d\udce3=============="];h.push(e),s&&h.push(s),i&&h.push(i),console.log(h.join("\n")),this.logs=this.logs.concat(h)}log(...t){t.length>0&&(this.logs=[...this.logs,...t]),console.log(t.join(this.logSeparator))}logErr(t,e){const s=!this.isSurge()&&!this.isQuanX()&&!this.isLoon();s?this.log("",`\u2757\ufe0f${this.name}, \u9519\u8bef!`,t.stack):this.log("",`\u2757\ufe0f${this.name}, \u9519\u8bef!`,t)}wait(t){return new Promise(e=>setTimeout(e,t))}done(t={}){const e=(new Date).getTime(),s=(e-this.startTime)/1e3;this.log("",`\ud83d\udd14${this.name}, \u7ed3\u675f! \ud83d\udd5b ${s} \u79d2`),this.log(),(this.isSurge()||this.isQuanX()||this.isLoon())&&$done(t)}}(t,e)} diff --git a/Task/translate.js b/Task/translate.js index 2b36cdf121..2e4c95bf9a 100644 --- a/Task/translate.js +++ b/Task/translate.js @@ -31,12 +31,12 @@ const cnToenUrl = {url: "http://translate.google.cn/translate_a/single?client=gt const enTocnUrl = {url: "http://translate.google.cn/translate_a/single?client=gtx&sl=auto&tl=zh-CN&dt=t&q="+setword}; !(async() => { -if (/[^a-zA-Z.,]+$/.test(ENword)){ +if (/[a-zA-Z.,]+$/.test(ENword)){ await ENWORD() } -if (/[^\u4e00-\u9fa5]+$/.test(ENword)) +if (/[\u4e00-\u9fa5]+$/.test(ENword)) { - await ENWORD() + await CNWORD() } })() .catch((e) => $.logErr(e)) diff --git a/Task/tvpreview.js b/Task/tvpreview.js index b8aca9019f..27fab59526 100644 --- a/Task/tvpreview.js +++ b/Task/tvpreview.js @@ -36,66 +36,51 @@ const $ = new Env("电视预告") const tvnum = $.getdata("c")||tv -const d = new Date(); - weekday = new Array(7); - weekday[0]="星期日"; - weekday[1]="星期一"; - weekday[2]="星期二"; - weekday[3]="星期三"; - weekday[4]="星期四"; - weekday[5]="星期五"; - weekday[6]="星期六"; - n = weekday[d.getDay()] +const weekday = new Array('星期日','星期一','星期二','星期三','星期四','星期五','星期六') + week = weekday[new Date().getDay()] - !(async () => { - await playTV(); - //await showmsg() -})() - .catch((e) => $.logErr(e)) - .finally(() => $.done()) -function playTV(){ -return new Promise((resolve) => { -const wurl = { - url: "http://api.cntv.cn/epg/epginfo?serviceId=cbox&c="+tvnum, - headers: {'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_5_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148'}, -} - $.get(wurl, (error, resp, data) => { - try { - let result = JSON.parse(data) - //console.log(result) - $.title = `${result[`${tvnum}`].channelName}频道节目 ` + $.time('MM月dd日') + $.time('H:m')+n - nowplay = `正在播出: ${result[`${tvnum}`].isLive}` - let playlist = "" - let playtime = "" - for (i = 0; i < result[`${tvnum}`].program.length; i++) - { - playdata = result[`${tvnum}`].program[i] - playtime = "\n"+playdata.showTime - duration = " 时长:"+Math.trunc(playdata.duration/60)+"分钟" - playitem = playdata.t - playlist += playtime+" "+playitem - } - $.detail = nowplay + playlist - let l = result[`${tvnum}`].program.length - for (i = 1; i < l && result[`${tvnum}`].program[i].showTime.split(':')[0] < result[`${tvnum}`].program[l-1].showTime.split(':')[0]; i++) - { - if (result[`${tvnum}`].liveSt == result[`${tvnum}`].program[i].st) - { - duration = " 时长: "+Math.trunc(result[`${tvnum}`].program[i+1].duration/60)+"分钟" - $.subTitle = `即将播出: ${result[`${tvnum}`].program[i+1].t}` +duration - } - } - $.msg($.title, $.subTitle, $.detail,{'media-url':`http://cdn.dianshihome.com/static/channel/poster/${tvnum}.jpg`}) - resolve() - } - catch(err) { - $.msg("无此频道节目信息或者台号错误❌", "请检查后重试", err) + +playTV(); + +function playTV() { + return new Promise((resolve) =>{ + const wurl = { + url: "http://api.cntv.cn/epg/epginfo?serviceId=cbox&c=" + tvnum, + headers: { + 'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148' + }, + } + $.get(wurl, (error, resp, data) =>{ + try { + let result = JSON.parse(data)[tvnum]; + //$.log(JSON.stringify(result,null,2)) + $.title = result.channelName + "频道节目 " + $.time('MM月dd日HH:mm ') + week; + $.sub = "正在播出: " + result.isLive; + liveUrl = result.lvUrl; + let playlist = ""; + for (i = 0; i < result.program.length; i++) { + playdata = result.program[i]; + playtime = "\n " + playdata.showTime, + duration = " 时长:" + Math.trunc(playdata.duration / 60) + "分钟", + playitem = playdata.t, + playlist += playtime + " " + playitem, + endTime = playdata.et - parseInt(Date.now() / 1000); + if (playdata.st == result.liveSt) { + $.sub += " 剩余" + parseInt(endTime / 60) + "分钟" + if (i + 1 < result.program.length) { + nextplay = "即将播出: " + result.program[i + 1].t + duration + } + } + } + $.desc = nextplay + playlist; + $.msg($.title, $.sub, $.desc, {'media-url': `http://cdn.dianshihome.com/static/channel/poster/${tvnum}.jpg`,'open-url':liveUrl}) + } catch(err) { + $.msg("无此频道节目信息或者台号错误❌", "请检查后重试", err) + } finally { + $.done() } - }) - }) + }) + }) } - - //console.log(playlist) - -function Env(t,e){class s{constructor(t){this.env=t}send(t,e="GET"){t="string"==typeof t?{url:t}:t;let s=this.get;return"POST"===e&&(s=this.post),new Promise((e,i)=>{s.call(this,t,(t,s,r)=>{t?i(t):e(s)})})}get(t){return this.send.call(this.env,t)}post(t){return this.send.call(this.env,t,"POST")}}return new class{constructor(t,e){this.name=t,this.http=new s(this),this.data=null,this.dataFile="box.dat",this.logs=[],this.isMute=!1,this.isNeedRewrite=!1,this.logSeparator="\n",this.startTime=(new Date).getTime(),Object.assign(this,e),this.log("",`\ud83d\udd14${this.name}, \u5f00\u59cb!`)}isNode(){return"undefined"!=typeof module&&!!module.exports}isQuanX(){return"undefined"!=typeof $task}isSurge(){return"undefined"!=typeof $httpClient&&"undefined"==typeof $loon}isLoon(){return"undefined"!=typeof $loon}toObj(t,e=null){try{return JSON.parse(t)}catch{return e}}toStr(t,e=null){try{return JSON.stringify(t)}catch{return e}}getjson(t,e){let s=e;const i=this.getdata(t);if(i)try{s=JSON.parse(this.getdata(t))}catch{}return s}setjson(t,e){try{return this.setdata(JSON.stringify(t),e)}catch{return!1}}getScript(t){return new Promise(e=>{this.get({url:t},(t,s,i)=>e(i))})}runScript(t,e){return new Promise(s=>{let i=this.getdata("@chavy_boxjs_userCfgs.httpapi");i=i?i.replace(/\n/g,"").trim():i;let r=this.getdata("@chavy_boxjs_userCfgs.httpapi_timeout");r=r?1*r:20,r=e&&e.timeout?e.timeout:r;const[o,h]=i.split("@"),a={url:`http://${h}/v1/scripting/evaluate`,body:{script_text:t,mock_type:"cron",timeout:r},headers:{"X-Key":o,Accept:"*/*"}};this.post(a,(t,e,i)=>s(i))}).catch(t=>this.logErr(t))}loaddata(){if(!this.isNode())return{};{this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(this.dataFile),e=this.path.resolve(process.cwd(),this.dataFile),s=this.fs.existsSync(t),i=!s&&this.fs.existsSync(e);if(!s&&!i)return{};{const i=s?t:e;try{return JSON.parse(this.fs.readFileSync(i))}catch(t){return{}}}}}writedata(){if(this.isNode()){this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(this.dataFile),e=this.path.resolve(process.cwd(),this.dataFile),s=this.fs.existsSync(t),i=!s&&this.fs.existsSync(e),r=JSON.stringify(this.data);s?this.fs.writeFileSync(t,r):i?this.fs.writeFileSync(e,r):this.fs.writeFileSync(t,r)}}lodash_get(t,e,s){const i=e.replace(/\[(\d+)\]/g,".$1").split(".");let r=t;for(const t of i)if(r=Object(r)[t],void 0===r)return s;return r}lodash_set(t,e,s){return Object(t)!==t?t:(Array.isArray(e)||(e=e.toString().match(/[^.[\]]+/g)||[]),e.slice(0,-1).reduce((t,s,i)=>Object(t[s])===t[s]?t[s]:t[s]=Math.abs(e[i+1])>>0==+e[i+1]?[]:{},t)[e[e.length-1]]=s,t)}getdata(t){let e=this.getval(t);if(/^@/.test(t)){const[,s,i]=/^@(.*?)\.(.*?)$/.exec(t),r=s?this.getval(s):"";if(r)try{const t=JSON.parse(r);e=t?this.lodash_get(t,i,""):e}catch(t){e=""}}return e}setdata(t,e){let s=!1;if(/^@/.test(e)){const[,i,r]=/^@(.*?)\.(.*?)$/.exec(e),o=this.getval(i),h=i?"null"===o?null:o||"{}":"{}";try{const e=JSON.parse(h);this.lodash_set(e,r,t),s=this.setval(JSON.stringify(e),i)}catch(e){const o={};this.lodash_set(o,r,t),s=this.setval(JSON.stringify(o),i)}}else s=this.setval(t,e);return s}getval(t){return this.isSurge()||this.isLoon()?$persistentStore.read(t):this.isQuanX()?$prefs.valueForKey(t):this.isNode()?(this.data=this.loaddata(),this.data[t]):this.data&&this.data[t]||null}setval(t,e){return this.isSurge()||this.isLoon()?$persistentStore.write(t,e):this.isQuanX()?$prefs.setValueForKey(t,e):this.isNode()?(this.data=this.loaddata(),this.data[e]=t,this.writedata(),!0):this.data&&this.data[e]||null}initGotEnv(t){this.got=this.got?this.got:require("got"),this.cktough=this.cktough?this.cktough:require("tough-cookie"),this.ckjar=this.ckjar?this.ckjar:new this.cktough.CookieJar,t&&(t.headers=t.headers?t.headers:{},void 0===t.headers.Cookie&&void 0===t.cookieJar&&(t.cookieJar=this.ckjar))}get(t,e=(()=>{})){t.headers&&(delete t.headers["Content-Type"],delete t.headers["Content-Length"]),this.isSurge()||this.isLoon()?(this.isSurge()&&this.isNeedRewrite&&(t.headers=t.headers||{},Object.assign(t.headers,{"X-Surge-Skip-Scripting":!1})),$httpClient.get(t,(t,s,i)=>{!t&&s&&(s.body=i,s.statusCode=s.status),e(t,s,i)})):this.isQuanX()?(this.isNeedRewrite&&(t.opts=t.opts||{},Object.assign(t.opts,{hints:!1})),$task.fetch(t).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>e(t))):this.isNode()&&(this.initGotEnv(t),this.got(t).on("redirect",(t,e)=>{try{if(t.headers["set-cookie"]){const s=t.headers["set-cookie"].map(this.cktough.Cookie.parse).toString();this.ckjar.setCookieSync(s,null),e.cookieJar=this.ckjar}}catch(t){this.logErr(t)}}).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>{const{message:s,response:i}=t;e(s,i,i&&i.body)}))}post(t,e=(()=>{})){if(t.body&&t.headers&&!t.headers["Content-Type"]&&(t.headers["Content-Type"]="application/x-www-form-urlencoded"),t.headers&&delete t.headers["Content-Length"],this.isSurge()||this.isLoon())this.isSurge()&&this.isNeedRewrite&&(t.headers=t.headers||{},Object.assign(t.headers,{"X-Surge-Skip-Scripting":!1})),$httpClient.post(t,(t,s,i)=>{!t&&s&&(s.body=i,s.statusCode=s.status),e(t,s,i)});else if(this.isQuanX())t.method="POST",this.isNeedRewrite&&(t.opts=t.opts||{},Object.assign(t.opts,{hints:!1})),$task.fetch(t).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>e(t));else if(this.isNode()){this.initGotEnv(t);const{url:s,...i}=t;this.got.post(s,i).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>{const{message:s,response:i}=t;e(s,i,i&&i.body)})}}time(t){let e={"M+":(new Date).getMonth()+1,"d+":(new Date).getDate(),"H+":(new Date).getHours(),"m+":(new Date).getMinutes(),"s+":(new Date).getSeconds(),"q+":Math.floor(((new Date).getMonth()+3)/3),S:(new Date).getMilliseconds()};/(y+)/.test(t)&&(t=t.replace(RegExp.$1,((new Date).getFullYear()+"").substr(4-RegExp.$1.length)));for(let s in e)new RegExp("("+s+")").test(t)&&(t=t.replace(RegExp.$1,1==RegExp.$1.length?e[s]:("00"+e[s]).substr((""+e[s]).length)));return t}msg(e=t,s="",i="",r){const o=t=>{if(!t)return t;if("string"==typeof t)return this.isLoon()?t:this.isQuanX()?{"open-url":t}:this.isSurge()?{url:t}:void 0;if("object"==typeof t){if(this.isLoon()){let e=t.openUrl||t.url||t["open-url"],s=t.mediaUrl||t["media-url"];return{openUrl:e,mediaUrl:s}}if(this.isQuanX()){let e=t["open-url"]||t.url||t.openUrl,s=t["media-url"]||t.mediaUrl;return{"open-url":e,"media-url":s}}if(this.isSurge()){let e=t.url||t.openUrl||t["open-url"];return{url:e}}}};this.isMute||(this.isSurge()||this.isLoon()?$notification.post(e,s,i,o(r)):this.isQuanX()&&$notify(e,s,i,o(r)));let h=["","==============\ud83d\udce3\u7cfb\u7edf\u901a\u77e5\ud83d\udce3=============="];h.push(e),s&&h.push(s),i&&h.push(i),console.log(h.join("\n")),this.logs=this.logs.concat(h)}log(...t){t.length>0&&(this.logs=[...this.logs,...t]),console.log(t.join(this.logSeparator))}logErr(t,e){const s=!this.isSurge()&&!this.isQuanX()&&!this.isLoon();s?this.log("",`\u2757\ufe0f${this.name}, \u9519\u8bef!`,t.stack):this.log("",`\u2757\ufe0f${this.name}, \u9519\u8bef!`,t)}wait(t){return new Promise(e=>setTimeout(e,t))}done(t={}){const e=(new Date).getTime(),s=(e-this.startTime)/1e3;this.log("",`\ud83d\udd14${this.name}, \u7ed3\u675f! \ud83d\udd5b ${s} \u79d2`),this.log(),(this.isSurge()||this.isQuanX()||this.isLoon())&&$done(t)}}(t,e)} \ No newline at end of file +function Env(t,e){class s{constructor(t){this.env=t}send(t,e="GET"){t="string"==typeof t?{url:t}:t;let s=this.get;return"POST"===e&&(s=this.post),new Promise((e,i)=>{s.call(this,t,(t,s,r)=>{t?i(t):e(s)})})}get(t){return this.send.call(this.env,t)}post(t){return this.send.call(this.env,t,"POST")}}return new class{constructor(t,e){this.name=t,this.http=new s(this),this.data=null,this.dataFile="box.dat",this.logs=[],this.isMute=!1,this.isNeedRewrite=!1,this.logSeparator="\n",this.startTime=(new Date).getTime(),Object.assign(this,e),this.log("",`\ud83d\udd14${this.name}, \u5f00\u59cb!`)}isNode(){return"undefined"!=typeof module&&!!module.exports}isQuanX(){return"undefined"!=typeof $task}isSurge(){return"undefined"!=typeof $httpClient&&"undefined"==typeof $loon}isLoon(){return"undefined"!=typeof $loon}toObj(t,e=null){try{return JSON.parse(t)}catch{return e}}toStr(t,e=null){try{return JSON.stringify(t)}catch{return e}}getjson(t,e){let s=e;const i=this.getdata(t);if(i)try{s=JSON.parse(this.getdata(t))}catch{}return s}setjson(t,e){try{return this.setdata(JSON.stringify(t),e)}catch{return!1}}getScript(t){return new Promise(e=>{this.get({url:t},(t,s,i)=>e(i))})}runScript(t,e){return new Promise(s=>{let i=this.getdata("@chavy_boxjs_userCfgs.httpapi");i=i?i.replace(/\n/g,"").trim():i;let r=this.getdata("@chavy_boxjs_userCfgs.httpapi_timeout");r=r?1*r:20,r=e&&e.timeout?e.timeout:r;const[o,h]=i.split("@"),a={url:`http://${h}/v1/scripting/evaluate`,body:{script_text:t,mock_type:"cron",timeout:r},headers:{"X-Key":o,Accept:"*/*"}};this.post(a,(t,e,i)=>s(i))}).catch(t=>this.logErr(t))}loaddata(){if(!this.isNode())return{};{this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(this.dataFile),e=this.path.resolve(process.cwd(),this.dataFile),s=this.fs.existsSync(t),i=!s&&this.fs.existsSync(e);if(!s&&!i)return{};{const i=s?t:e;try{return JSON.parse(this.fs.readFileSync(i))}catch(t){return{}}}}}writedata(){if(this.isNode()){this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(this.dataFile),e=this.path.resolve(process.cwd(),this.dataFile),s=this.fs.existsSync(t),i=!s&&this.fs.existsSync(e),r=JSON.stringify(this.data);s?this.fs.writeFileSync(t,r):i?this.fs.writeFileSync(e,r):this.fs.writeFileSync(t,r)}}lodash_get(t,e,s){const i=e.replace(/\[(\d+)\]/g,".$1").split(".");let r=t;for(const t of i)if(r=Object(r)[t],void 0===r)return s;return r}lodash_set(t,e,s){return Object(t)!==t?t:(Array.isArray(e)||(e=e.toString().match(/[^.[\]]+/g)||[]),e.slice(0,-1).reduce((t,s,i)=>Object(t[s])===t[s]?t[s]:t[s]=Math.abs(e[i+1])>>0==+e[i+1]?[]:{},t)[e[e.length-1]]=s,t)}getdata(t){let e=this.getval(t);if(/^@/.test(t)){const[,s,i]=/^@(.*?)\.(.*?)$/.exec(t),r=s?this.getval(s):"";if(r)try{const t=JSON.parse(r);e=t?this.lodash_get(t,i,""):e}catch(t){e=""}}return e}setdata(t,e){let s=!1;if(/^@/.test(e)){const[,i,r]=/^@(.*?)\.(.*?)$/.exec(e),o=this.getval(i),h=i?"null"===o?null:o||"{}":"{}";try{const e=JSON.parse(h);this.lodash_set(e,r,t),s=this.setval(JSON.stringify(e),i)}catch(e){const o={};this.lodash_set(o,r,t),s=this.setval(JSON.stringify(o),i)}}else s=this.setval(t,e);return s}getval(t){return this.isSurge()||this.isLoon()?$persistentStore.read(t):this.isQuanX()?$prefs.valueForKey(t):this.isNode()?(this.data=this.loaddata(),this.data[t]):this.data&&this.data[t]||null}setval(t,e){return this.isSurge()||this.isLoon()?$persistentStore.write(t,e):this.isQuanX()?$prefs.setValueForKey(t,e):this.isNode()?(this.data=this.loaddata(),this.data[e]=t,this.writedata(),!0):this.data&&this.data[e]||null}initGotEnv(t){this.got=this.got?this.got:require("got"),this.cktough=this.cktough?this.cktough:require("tough-cookie"),this.ckjar=this.ckjar?this.ckjar:new this.cktough.CookieJar,t&&(t.headers=t.headers?t.headers:{},void 0===t.headers.Cookie&&void 0===t.cookieJar&&(t.cookieJar=this.ckjar))}get(t,e=(()=>{})){t.headers&&(delete t.headers["Content-Type"],delete t.headers["Content-Length"]),this.isSurge()||this.isLoon()?(this.isSurge()&&this.isNeedRewrite&&(t.headers=t.headers||{},Object.assign(t.headers,{"X-Surge-Skip-Scripting":!1})),$httpClient.get(t,(t,s,i)=>{!t&&s&&(s.body=i,s.statusCode=s.status),e(t,s,i)})):this.isQuanX()?(this.isNeedRewrite&&(t.opts=t.opts||{},Object.assign(t.opts,{hints:!1})),$task.fetch(t).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>e(t))):this.isNode()&&(this.initGotEnv(t),this.got(t).on("redirect",(t,e)=>{try{if(t.headers["set-cookie"]){const s=t.headers["set-cookie"].map(this.cktough.Cookie.parse).toString();this.ckjar.setCookieSync(s,null),e.cookieJar=this.ckjar}}catch(t){this.logErr(t)}}).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>{const{message:s,response:i}=t;e(s,i,i&&i.body)}))}post(t,e=(()=>{})){if(t.body&&t.headers&&!t.headers["Content-Type"]&&(t.headers["Content-Type"]="application/x-www-form-urlencoded"),t.headers&&delete t.headers["Content-Length"],this.isSurge()||this.isLoon())this.isSurge()&&this.isNeedRewrite&&(t.headers=t.headers||{},Object.assign(t.headers,{"X-Surge-Skip-Scripting":!1})),$httpClient.post(t,(t,s,i)=>{!t&&s&&(s.body=i,s.statusCode=s.status),e(t,s,i)});else if(this.isQuanX())t.method="POST",this.isNeedRewrite&&(t.opts=t.opts||{},Object.assign(t.opts,{hints:!1})),$task.fetch(t).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>e(t));else if(this.isNode()){this.initGotEnv(t);const{url:s,...i}=t;this.got.post(s,i).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>{const{message:s,response:i}=t;e(s,i,i&&i.body)})}}time(t){let e={"M+":(new Date).getMonth()+1,"d+":(new Date).getDate(),"H+":(new Date).getHours(),"m+":(new Date).getMinutes(),"s+":(new Date).getSeconds(),"q+":Math.floor(((new Date).getMonth()+3)/3),S:(new Date).getMilliseconds()};/(y+)/.test(t)&&(t=t.replace(RegExp.$1,((new Date).getFullYear()+"").substr(4-RegExp.$1.length)));for(let s in e)new RegExp("("+s+")").test(t)&&(t=t.replace(RegExp.$1,1==RegExp.$1.length?e[s]:("00"+e[s]).substr((""+e[s]).length)));return t}msg(e=t,s="",i="",r){const o=t=>{if(!t)return t;if("string"==typeof t)return this.isLoon()?t:this.isQuanX()?{"open-url":t}:this.isSurge()?{url:t}:void 0;if("object"==typeof t){if(this.isLoon()){let e=t.openUrl||t.url||t["open-url"],s=t.mediaUrl||t["media-url"];return{openUrl:e,mediaUrl:s}}if(this.isQuanX()){let e=t["open-url"]||t.url||t.openUrl,s=t["media-url"]||t.mediaUrl;return{"open-url":e,"media-url":s}}if(this.isSurge()){let e=t.url||t.openUrl||t["open-url"];return{url:e}}}};this.isMute||(this.isSurge()||this.isLoon()?$notification.post(e,s,i,o(r)):this.isQuanX()&&$notify(e,s,i,o(r)));let h=["","==============\ud83d\udce3\u7cfb\u7edf\u901a\u77e5\ud83d\udce3=============="];h.push(e),s&&h.push(s),i&&h.push(i),console.log(h.join("\n")),this.logs=this.logs.concat(h)}log(...t){t.length>0&&(this.logs=[...this.logs,...t]),console.log(t.join(this.logSeparator))}logErr(t,e){const s=!this.isSurge()&&!this.isQuanX()&&!this.isLoon();s?this.log("",`\u2757\ufe0f${this.name}, \u9519\u8bef!`,t.stack):this.log("",`\u2757\ufe0f${this.name}, \u9519\u8bef!`,t)}wait(t){return new Promise(e=>setTimeout(e,t))}done(t={}){const e=(new Date).getTime(),s=(e-this.startTime)/1e3;this.log("",`\ud83d\udd14${this.name}, \u7ed3\u675f! \ud83d\udd5b ${s} \u79d2`),this.log(),(this.isSurge()||this.isQuanX()||this.isLoon())&&$done(t)}}(t,e)} diff --git a/Task/txnews.js b/Task/txnews.js index 63dc1b103b..473206910e 100644 --- a/Task/txnews.js +++ b/Task/txnews.js @@ -1,60 +1,19 @@ /* -更新时间: 2020-10-16 20:10 +更新时间: 2021-02-18 11:15 -腾讯新闻签到修改版,可以自动阅读文章获取红包,该活动为瓜分百万现金挑战赛,针对幸运用户参与 - -获取Cookie方法: -1.把以下配置复制到响应配置下 -2.打开腾讯新闻app,阅读几篇文章,倒计时结束后即可获取阅读Cookie; -3.看一次推荐视频获取视频地址 -4.可能腾讯有某些限制,有些号码无法领取红包,手动阅读几篇,能领取红包,一般情况下都是正常的, -5.此脚本根据阅读篇数开启通知,默认阅读50篇通知一次,此版本和另一版本相同 -版本更新日志: -1.01 修复无法自动获取视频红包,修改通知为阅读篇数间隔,即阅读篇数除以间隔余0时通知,或者自定义常开或常关, -1.02 支持boxjs配置,增加通知跳转链接https://news.qq.com/FERD/cjRedDown.htm,需手动领取此红包 ---------------------- -Surge 4.0 -[Script] -腾讯新闻 = type=cron,cronexp=0 8 0 * * *,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/txnews.js,script-update-interval=0 - -腾讯新闻 = type=http-request,pattern=https:\/\/api\.inews\.qq\.com\/event\/v1\/user\/event\/report\?,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/txnews.js, requires-body=true - -~~~~~~~~~~~~~~~~~~~~~ -Loon 2.1.0+ -[Script] -# 本地脚本 -cron "04 00 * * *" script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/txnews.js, enabled=true, tag=腾讯新闻 - -http-request https:\/\/api\.inews\.qq\.com\/event\/v1\/user\/event\/report\? script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/txnews.js, requires-body=true - ------------------ - -QX 1.0.7+ : - [task_local] -0 9 * * * https://raw.githubusercontent.com/Sunert/Scripts/master/Task/txnews.js, tag=腾讯新闻 - [rewrite_local] -https:\/\/api\.inews\.qq\.com\/event\/v1\/user\/event\/report\? url script-request-body https://raw.githubusercontent.com/Sunert/Scripts/master/Task/txnews.js - -~~~~~~~~~~~~~~~~~~ - [MITM] -hostname = api.inews.qq.com - ---------------------------- - -Cookie获取后,请注释掉Cookie地址。 +腾讯新闻签到修改版,可以自动阅读文章获取红包,该活动为瓜分百万现金挑战赛,针对幸运用户参与,本脚本已不能自动打开红包,需每天要打开腾讯新闻app一次,请须知 */ const $ = new Env('腾讯新闻'); const notify = $.isNode() ? require('./sendNotify') : ''; -let s = parseInt($.getdata('delay'))||200 // 间隔延迟时间 let notifyInterval =$.getdata('notifynum')||50; //阅读篇数间隔通知开为1,常关为0; -const TX_HOST = 'https://api.inews.qq.com/activity/v1/' + let SignArr = [],SignUrl = ""; cookiesArr = [],CookieTxnews = ""; - VideoArr = [],SignUrl = ""; - - + VideoArr = [],SignUrl = "",order = "", + detail = ``, subTitle = ``; +let read_finish = "",video_finish=""; if ($.isNode()) { if (process.env.TXNEWS_COOKIE && process.env.TXNEWS_COOKIE.indexOf('&') > -1) { CookieTxnews = process.env.TXNEWS_COOKIE.split('&'); @@ -103,8 +62,10 @@ if (isGetCookie) { return } if ($.isNode()){ - console.log(`============ 脚本执行-国际标准时间(UTC):${new Date().toLocaleString()} =============\n`) - console.log(`============ 脚本执行-北京时间(UTC+8):${new Date(new Date().getTime() + 8 * 60 * 60 * 1000).toLocaleString()}=============\n`) + timeZone = new Date().getTimezoneOffset() / 60; + timestamp = Date.now()+ (8+timeZone) * 60 * 60 * 1000; + bjTime = new Date(timestamp).toLocaleString('zh',{hour12:false,timeZoneName: 'long'}); + console.log(`\n === 脚本执行 ${bjTime} ===\n`); } for (let i = 0; i < cookiesArr.length; i++) { if (cookiesArr[i]) { @@ -113,28 +74,20 @@ if (isGetCookie) { videoVal = VideoArr[i]; $.index = i + 1; console.log(`-------------------------\n\n开始【腾讯新闻账号${$.index}】`) - } - token = signurlVal.match(/devid=[a-zA-Z0-9_-]+/g)[0] + ID = signurlVal.match(/devid=[a-zA-Z0-9_-]+/g)[0] + token = signurlVal.split("mac")[1] await getsign(); await activity(); - await toRead(); - await lookVideo(); - await StepsTotal(); - if(getreadred > 0){ - redbody = `redpack_type=article&activity_id=${actid}` - await Redpack() - }; - if(getvideored>0){ - redbody = `redpack_type=video&activity_id=${actid}` - await Redpack() - }; await getTotal(); + await $.wait(1000); + await StepsTotal(); await showmsg(); - if ($.isNode()){ - if (readnum%notifyInterval==0&&Total_Earn.data.wealth[1].title > 2){ + if ($.isNode()&&process.env.TXNEWS_NOTIFY_CONTROL){ + if (readnum%notifyInterval==0&&cashtotal > 2){ await notify.sendNotify($.name,subTile+'\n'+detail) + } } - } + } } })() .catch((e) => $.logErr(e)) @@ -152,30 +105,48 @@ function GetCookie() { $.msg($.name, `获取Cookie: 成功🎉`, ``) } if ($request &&$request.body.indexOf("video_read")> -1) { - const videoVal = $request.url + const videoVal = $request.url $.log(`videoVal:${videoVal}`) if (videoVal) $.setdata(videoVal, 'video_txnews') $.msg($.name, `获取视频地址: 成功🎉`, ``) } } +function Host(api, body, taskurl) { + return { + url: 'https://api.inews.qq.com/activity/v1/'+api+'&isJailbreak=0&'+ID, + headers:{ + 'Accept': '*/*', + 'Accept-Encoding': 'gzip, deflate, br', + 'Accept-Language': 'zh-Hans-CN;q=1, en-CN;q=0.9, zh-Hant-CN;q=0.8', + 'Connection': 'keep-alive', + 'Cookie': cookieVal, + 'Host': 'api.inews.qq.com', + 'Referer': taskurl, + 'store': '1', + 'devid': ID, + 'User-Agent': 'QQNews/6.4.10 (iPhone; iOS 14.2; Scale/3.00)' + }, + body: body + } +} //签到 function getsign() { return new Promise((resolve, reject) => { const signUrl = { - url: `https://api.inews.qq.com/task/v1/user/signin/add?`,headers:{Cookie: cookieVal} + url: `https://api.inews.qq.com/task/v1/user/signin/add?`,headers: Host().headers }; - $.post(signUrl, (error, response, data) => { + $.post(signUrl, (error, resp, data) => { let obj = JSON.parse(data) +// $.log(JSON.stringify(obj,null,2)) if (obj.info=="success"){ next = obj.data.next_points tip = obj.data.tip_soup||obj.data.share_tip imgurl= obj.data.share_img - Dictum = tip.replace(/[\<|\.|\>|br]/g,"")+""+obj.data.author.replace(/[\<|\.|\>|br|图|腾讯网友]/g,"") - signinfo = '【签到信息】连续签到' + obj.data.signin_days+'天 '+'明日+'+ next +'金币 成功🎉\n'} - else { - $.msg('签到失败,🉐登录腾讯新闻app获取cookie', "", "") + Dictum = tip.replace(/
/g,"")+" "+obj.data.author + signinfo = '【签到信息】连续签到' + obj.data.signin_days+'天 '+'明日+'+ next +'金币 成功🎉\n'} else { + $.msg($.name, '签到失败,🉐登录腾讯新闻app获取cookie', "") console.log('签到失败,🉐登录腾讯新闻app获取cookie'+data) return } @@ -185,131 +156,183 @@ function getsign() { } function activity() { - return new Promise((resolve, reject) => { - setTimeout(()=>{ - $.get({url:`${TX_HOST}user/activity/get?isJailbreak=0&${token}`, headers: {Cookie:cookieVal}}, (error,response, data) =>{ - try{ - let obj = JSON.parse(data) - actid = obj.data.activity.id - console.log(` 您的活动ID为: `+actid+"\n") - } catch(error){ - $.msg("获取活动ID失败,详情请看日志","","") - console.log("活动ID日志:"+ data) + return new Promise((resolve, reject) =>{ + $.get(Host('user/task/list?'), async(error, resp, data) =>{ + try { + let taskres = JSON.parse(data); + //$.log(JSON.stringify(taskres,null,2)) + if (taskres.ret == 0) { + actid = taskres.data.award_notice.activity_id; + if(!actid){ + actid = $.getdata('txnews_id') + } + $.log(`\n您的活动ID为: ` + actid + "\n\n********* 开始阅读任务 ********\n"); + $.desc = "" + for (tasks of taskres.data.list) { + taskname = tasks.task_title, + tasktype = tasks.task_type, + taskstatus = tasks.task_status, + ratepack = tasks.rate, + totalpack = tasks.quota; + eventnum = tasks.task_desc + taskurl = tasks.task_url + $.log("去" + taskname + "\n"); + if (taskstatus == 3) { + $.desc += "【" + taskname + "】✅ 已完成\n"; + $.log(taskname + "已完成") + } else { + if (tasktype == "article") { + readnum = eventnum.match(/>(\d+)(.+)<\/span>分钟/)[1] + //$.desc += "【" + taskname + "】 已领" + ratepack + "个红包 已看"+videonum+"分钟\n"; + await $.wait(5000); + await toRead(videoVal, 'event=video_read') + } else if(tasktype == "cooperation") { + await openapp(tasks.task_id) + } + } } - resolve() - }) - },s) + } + } catch(error) { + $.msg($.name, "获取活动ID失败,详情请看日志", "", ""); + console.log("活动ID日志:" + data); + return + } + resolve() + }) }) } //阅读阶梯 -function toRead() { - return new Promise((resolve, reject) => { - setTimeout(()=>{ - $.post({url: signurlVal, headers: {Cookie:cookieVal}, body: 'event=article_read'},(error, resp, data)=> { - $.log("正在浏览文章"+data) - }) +function toRead(urlVal, body) { + return new Promise((resolve, reject) =>{ + $.post({ + url: urlVal, + headers: Host().headers, + body: body + },(error, resp, data) =>{ + try { + let obj = JSON.parse(data) + //$.log(JSON.stringify(obj,null,2)) + if (obj.ret == 0) { + console.log("本次阅读成功,获取收益" + obj.data.countdown_timer.countdown_tips + "\n"); + } else if (body.indexOf("article") > -1) { + console.log("本次阅读文章失败," + obj.info + "\n"); + } else if (body.indexOf("video") > -1) { + console.log("本次观看视频失败," + obj.info + "\n"); + } + } catch(error) { + console.log("本次阅读失败" + data + "\n") + } resolve() - },s) + }) }) } -function lookVideo() { - return new Promise((resolve, reject) => { - setTimeout(()=>{ - $.post({url: videoVal, headers: {Cookie:cookieVal},body: 'event=video_read'},(error, response, data) =>{ - if (error){ - $.msg($.name, '观看视频:'+ error) - }else{ - $.log("正在观看视频"+data) - tolookresult = JSON.parse(data) + +function openapp(taskid) { + return new Promise((resolve, reject) =>{ + $.get(Host('activity/do?activity_id='+taskid+'&'+ token), async(error, resp, data) =>{ + try { + let obj = JSON.parse(data) + $.log(JSON.stringify(obj,null,2)) + if (obj.ret == 0) { + $.log(taskname+"成功") + } else{ + $.log(taskname+"失败," + obj.info + "\n"); } - resolve() - }) - },s*2) + } catch(error) { + console.log("本次任务失败" + data + "\n") + } + resolve() + }) }) } + //阅读文章统计 function StepsTotal() { - return new Promise((resolve, reject) => { - setTimeout(()=>{ - const StepsUrl = { - url: `${TX_HOST}activity/info/get?activity_id=${actid}&${token}`, - headers: {Cookie: cookieVal} - } - $.get(StepsUrl, (error, response, data) => { - totalred = JSON.parse(data) - totalcion = totalred.data.extends.today_total_coin - if (totalred.ret == 0){ - for (i=0;i{ + $.get(Host('activity/info/get?activity_id=' + actid), async(error, resp, data) =>{ + totalred = JSON.parse(data); + //$.log(JSON.stringify(totalred,null,2)) + totalcion = totalred.data.extends.today_total_coin; + if (totalred.ret == 0) { + for (awards of totalred.data.award) { + taskType = awards.type, + red_get = awards.can_get, + redtotal = awards.total, + red_opened = awards.opened, + task_num = awards.event_num, + //readtitle = awards.title.split(",")[0].replace(/[\u4e00-\u9fa5]/g,``) + title = awards.title.match(/\d+/) + over_red = Number(redtotal - red_opened); + if (taskType == "article") { + read_res = over_red; + $.desc += "【阅读资讯】 已领" + awards.opened + "个红包 已看"+readnum+"篇/再读"+title+"篇\n"; + if (awards.openable !== 0) { + $.log("可以打开" + awards.openable + "个阅读红包,去打开红包"); + await $.wait(1000); + await Redpack(taskType) } - if(totalred.data.award[i].type=='video'){ - videoredtotal = totalred.data.award[i].total - videotitle = totalred.data.award[i].title.split(",")[0].replace(/[\u4e00-\u9fa5]/g,``) - getvideored = totalred.data.award[i].openable - openvideored = totalred.data.award[i].opened - videonum = totalred.data.award[i].event_num/2 + } + if (taskType == "video") { + video_res = over_red; + $.desc += "【观看视频】 已领" + awards.opened+ "个红包 已看"+videonum+"分钟/再读"+title+"分钟\n"; + if (awards.openable !== 0) { + $.log("可以打开" + awards.openable + "个视频红包,去打开红包"); + await $.wait(1000); + await Redpack(taskType) } } - // $.log(" 已阅读文章"+readnum+"篇\n 浏览视频"+videonum+"分钟\n 今日已打开"+(openreadred+openvideored)+"个红包\n 今日金币收益"+totalcion) } - resolve() - }) - },s) + } + resolve() + }) }) } //阶梯红包到账 -function Redpack() { - return new Promise((resolve, reject) => { - setTimeout(()=>{ - const cashUrl = { - url: `${TX_HOST}activity/redpack/get?isJailbreak=0&${token}`, - headers: {Cookie: cookieVal}, - body: redbody - } - $.post(cashUrl, (error, response, data) => { - let rcash = JSON.parse(data) - try{ - redpacks = rcash.data.award.num/100 - if (rcash.ret == 0&&redpacks>0&&getreadred > 0){ - redpackres = `【阅读红包】到账`+redpacks+`元 🌷\n` - $.log("阅读红包到账"+redpacks+"元\n") - } - else if (rcash.ret == 0&& redpacks >0){ - redpackres = `【视频红包】到账`+redpacks+`元 🌷\n` - $.log("视频红包到账"+redpacks+"元\n") +function Redpack(red_body) { + return new Promise((resolve, reject) =>{ + $.post(Host('activity/redpack/get?', `redpack_type=${red_body}&activity_id=${actid}`), (error, resp, data) =>{ + let rcash = JSON.parse(data); + try { + if (rcash.data.award.length == 1) { + redpacks = rcash.data.award.num / 100; + if (rcash.ret == 0 && redpacks > 0 && red_body == "article") { + redpackres = `【阅读红包】到账` + redpacks + `元🌷\n`; + $.log("阅读红包到账" + redpacks + "元\n") + } else if (rcash.ret == 0 && redpacks > 0 && red_body == "video") { + redpackres = `【视频红包】到账` + redpacks + `元🌷\n`; + $.log("视频红包到账" + redpacks + "元\n") } + } else { + $.log(rcash.data.award.length + "个红包到账\n") } - catch(error){ - $.log("打开红包失败,响应数据: "+ data+"\n错误代码:"+error) }; - $.msg($.name, "开红包失败,详情请看日志 ❌", error) - resolve() - }) - },s) + } catch(error) { + console.log("打开红包失败,响应数据: " + data); + $.msg($.name, "开红包失败,详情请看日志 ❌", error) + }; + resolve() + }) }) } //收益总计 function getTotal() { return new Promise((resolve, reject) => { - const totalUrl = { - url: `${TX_HOST}usercenter/activity/list?isJailbreak=0`, - headers: {Cookie: cookieVal}}; - $.post(totalUrl, function(error,response, data) { + $.post(Host('usercenter/activity/list?'), (error, resp, data) =>{ if (error) { $.msg("获取收益信息失败‼️", "", error) } else { const Total_Earn = JSON.parse(data) - subTile = '【收益总计】'+Total_Earn.data.wealth[0].title +'金币 '+"钱包: " +Total_Earn.data.wealth[1].title+'元' + cashtotal = Total_Earn.data.wealth[1].title + $.sub = '【收益总计】'+ Total_Earn.data.wealth[0].title +'金币 '+"钱包: " + cashtotal+'元' // $.log("钱包收益共计"+obj.data.wealth[1].title+"元") } resolve() @@ -319,19 +342,17 @@ function getTotal() { function showmsg() { return new Promise((resolve, reject) => { - if(readnum||videonum){ - detail = signinfo + `【文章阅读】已读/再读: `+ readnum +`/`+readtitle+` 篇\n`+`【阅读红包】已开/总计: `+openreadred+`/`+readredtotal+` 个🧧\n`+ `【观看视频】已看/再看: `+ videonum +`/`+videotitle+` 分钟\n`+`【视频红包】已开/总计: `+openvideored+`/`+videoredtotal+` 个🧧\n【每日一句】`+Dictum - } - console.log($.name+'\n'+subTile+'\n'+ detail) - if (readnum%notifyInterval==0){ - $.msg($.name,subTile,detail,{ 'open-url': "https://news.qq.com/FERD/cjRedDown.htm", 'media-url': imgurl } ) - } - else if (openreadred==readredtotal&&openvideored==videoredtotal){ - $.msg($.name+` 今日任务已完成✅`,subTile,detail,{ 'open-url': "https://news.qq.com/FERD/cjRedDown.htm", 'media-url': imgurl } ) - } + $.desc += '【每日一句】'+Dictum + if (readnum&&readnum%notifyInterval==0){ + $.msg($.name, $.sub, $.desc,{ 'open-url': "https://news.qq.com/FERD/cjRedDown.htm", 'media-url': imgurl } ) + } else if (read_res==0&&video_res==0){ + $.msg($.name+` 今日任务已完成✅`,$.sub, $.desc,{ 'open-url': "https://news.qq.com/FERD/cjRedDown.htm", 'media-url': imgurl } ) + } else { + console.log($.sub+'\n'+ $.desc) + } resolve() }) } // prettier-ignore -function Env(t,e){class s{constructor(t){this.env=t}send(t,e="GET"){t="string"==typeof t?{url:t}:t;let s=this.get;return"POST"===e&&(s=this.post),new Promise((e,i)=>{s.call(this,t,(t,s,r)=>{t?i(t):e(s)})})}get(t){return this.send.call(this.env,t)}post(t){return this.send.call(this.env,t,"POST")}}return new class{constructor(t,e){this.name=t,this.http=new s(this),this.data=null,this.dataFile="box.dat",this.logs=[],this.isMute=!1,this.isNeedRewrite=!1,this.logSeparator="\n",this.startTime=(new Date).getTime(),Object.assign(this,e),this.log("",`\ud83d\udd14${this.name}, \u5f00\u59cb!`)}isNode(){return"undefined"!=typeof module&&!!module.exports}isQuanX(){return"undefined"!=typeof $task}isSurge(){return"undefined"!=typeof $httpClient&&"undefined"==typeof $loon}isLoon(){return"undefined"!=typeof $loon}toObj(t,e=null){try{return JSON.parse(t)}catch{return e}}toStr(t,e=null){try{return JSON.stringify(t)}catch{return e}}getjson(t,e){let s=e;const i=this.getdata(t);if(i)try{s=JSON.parse(this.getdata(t))}catch{}return s}setjson(t,e){try{return this.setdata(JSON.stringify(t),e)}catch{return!1}}getScript(t){return new Promise(e=>{this.get({url:t},(t,s,i)=>e(i))})}runScript(t,e){return new Promise(s=>{let i=this.getdata("@chavy_boxjs_userCfgs.httpapi");i=i?i.replace(/\n/g,"").trim():i;let r=this.getdata("@chavy_boxjs_userCfgs.httpapi_timeout");r=r?1*r:20,r=e&&e.timeout?e.timeout:r;const[o,h]=i.split("@"),a={url:`http://${h}/v1/scripting/evaluate`,body:{script_text:t,mock_type:"cron",timeout:r},headers:{"X-Key":o,Accept:"*/*"}};this.post(a,(t,e,i)=>s(i))}).catch(t=>this.logErr(t))}loaddata(){if(!this.isNode())return{};{this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(this.dataFile),e=this.path.resolve(process.cwd(),this.dataFile),s=this.fs.existsSync(t),i=!s&&this.fs.existsSync(e);if(!s&&!i)return{};{const i=s?t:e;try{return JSON.parse(this.fs.readFileSync(i))}catch(t){return{}}}}}writedata(){if(this.isNode()){this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(this.dataFile),e=this.path.resolve(process.cwd(),this.dataFile),s=this.fs.existsSync(t),i=!s&&this.fs.existsSync(e),r=JSON.stringify(this.data);s?this.fs.writeFileSync(t,r):i?this.fs.writeFileSync(e,r):this.fs.writeFileSync(t,r)}}lodash_get(t,e,s){const i=e.replace(/\[(\d+)\]/g,".$1").split(".");let r=t;for(const t of i)if(r=Object(r)[t],void 0===r)return s;return r}lodash_set(t,e,s){return Object(t)!==t?t:(Array.isArray(e)||(e=e.toString().match(/[^.[\]]+/g)||[]),e.slice(0,-1).reduce((t,s,i)=>Object(t[s])===t[s]?t[s]:t[s]=Math.abs(e[i+1])>>0==+e[i+1]?[]:{},t)[e[e.length-1]]=s,t)}getdata(t){let e=this.getval(t);if(/^@/.test(t)){const[,s,i]=/^@(.*?)\.(.*?)$/.exec(t),r=s?this.getval(s):"";if(r)try{const t=JSON.parse(r);e=t?this.lodash_get(t,i,""):e}catch(t){e=""}}return e}setdata(t,e){let s=!1;if(/^@/.test(e)){const[,i,r]=/^@(.*?)\.(.*?)$/.exec(e),o=this.getval(i),h=i?"null"===o?null:o||"{}":"{}";try{const e=JSON.parse(h);this.lodash_set(e,r,t),s=this.setval(JSON.stringify(e),i)}catch(e){const o={};this.lodash_set(o,r,t),s=this.setval(JSON.stringify(o),i)}}else s=this.setval(t,e);return s}getval(t){return this.isSurge()||this.isLoon()?$persistentStore.read(t):this.isQuanX()?$prefs.valueForKey(t):this.isNode()?(this.data=this.loaddata(),this.data[t]):this.data&&this.data[t]||null}setval(t,e){return this.isSurge()||this.isLoon()?$persistentStore.write(t,e):this.isQuanX()?$prefs.setValueForKey(t,e):this.isNode()?(this.data=this.loaddata(),this.data[e]=t,this.writedata(),!0):this.data&&this.data[e]||null}initGotEnv(t){this.got=this.got?this.got:require("got"),this.cktough=this.cktough?this.cktough:require("tough-cookie"),this.ckjar=this.ckjar?this.ckjar:new this.cktough.CookieJar,t&&(t.headers=t.headers?t.headers:{},void 0===t.headers.Cookie&&void 0===t.cookieJar&&(t.cookieJar=this.ckjar))}get(t,e=(()=>{})){t.headers&&(delete t.headers["Content-Type"],delete t.headers["Content-Length"]),this.isSurge()||this.isLoon()?(this.isSurge()&&this.isNeedRewrite&&(t.headers=t.headers||{},Object.assign(t.headers,{"X-Surge-Skip-Scripting":!1})),$httpClient.get(t,(t,s,i)=>{!t&&s&&(s.body=i,s.statusCode=s.status),e(t,s,i)})):this.isQuanX()?(this.isNeedRewrite&&(t.opts=t.opts||{},Object.assign(t.opts,{hints:!1})),$task.fetch(t).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>e(t))):this.isNode()&&(this.initGotEnv(t),this.got(t).on("redirect",(t,e)=>{try{if(t.headers["set-cookie"]){const s=t.headers["set-cookie"].map(this.cktough.Cookie.parse).toString();this.ckjar.setCookieSync(s,null),e.cookieJar=this.ckjar}}catch(t){this.logErr(t)}}).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>{const{message:s,response:i}=t;e(s,i,i&&i.body)}))}post(t,e=(()=>{})){if(t.body&&t.headers&&!t.headers["Content-Type"]&&(t.headers["Content-Type"]="application/x-www-form-urlencoded"),t.headers&&delete t.headers["Content-Length"],this.isSurge()||this.isLoon())this.isSurge()&&this.isNeedRewrite&&(t.headers=t.headers||{},Object.assign(t.headers,{"X-Surge-Skip-Scripting":!1})),$httpClient.post(t,(t,s,i)=>{!t&&s&&(s.body=i,s.statusCode=s.status),e(t,s,i)});else if(this.isQuanX())t.method="POST",this.isNeedRewrite&&(t.opts=t.opts||{},Object.assign(t.opts,{hints:!1})),$task.fetch(t).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>e(t));else if(this.isNode()){this.initGotEnv(t);const{url:s,...i}=t;this.got.post(s,i).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>{const{message:s,response:i}=t;e(s,i,i&&i.body)})}}time(t){let e={"M+":(new Date).getMonth()+1,"d+":(new Date).getDate(),"H+":(new Date).getHours(),"m+":(new Date).getMinutes(),"s+":(new Date).getSeconds(),"q+":Math.floor(((new Date).getMonth()+3)/3),S:(new Date).getMilliseconds()};/(y+)/.test(t)&&(t=t.replace(RegExp.$1,((new Date).getFullYear()+"").substr(4-RegExp.$1.length)));for(let s in e)new RegExp("("+s+")").test(t)&&(t=t.replace(RegExp.$1,1==RegExp.$1.length?e[s]:("00"+e[s]).substr((""+e[s]).length)));return t}msg(e=t,s="",i="",r){const o=t=>{if(!t)return t;if("string"==typeof t)return this.isLoon()?t:this.isQuanX()?{"open-url":t}:this.isSurge()?{url:t}:void 0;if("object"==typeof t){if(this.isLoon()){let e=t.openUrl||t.url||t["open-url"],s=t.mediaUrl||t["media-url"];return{openUrl:e,mediaUrl:s}}if(this.isQuanX()){let e=t["open-url"]||t.url||t.openUrl,s=t["media-url"]||t.mediaUrl;return{"open-url":e,"media-url":s}}if(this.isSurge()){let e=t.url||t.openUrl||t["open-url"];return{url:e}}}};this.isMute||(this.isSurge()||this.isLoon()?$notification.post(e,s,i,o(r)):this.isQuanX()&&$notify(e,s,i,o(r)));let h=["","==============\ud83d\udce3\u7cfb\u7edf\u901a\u77e5\ud83d\udce3=============="];h.push(e),s&&h.push(s),i&&h.push(i),console.log(h.join("\n")),this.logs=this.logs.concat(h)}log(...t){t.length>0&&(this.logs=[...this.logs,...t]),console.log(t.join(this.logSeparator))}logErr(t,e){const s=!this.isSurge()&&!this.isQuanX()&&!this.isLoon();s?this.log("",`\u2757\ufe0f${this.name}, \u9519\u8bef!`,t.stack):this.log("",`\u2757\ufe0f${this.name}, \u9519\u8bef!`,t)}wait(t){return new Promise(e=>setTimeout(e,t))}done(t={}){const e=(new Date).getTime(),s=(e-this.startTime)/1e3;this.log("",`\ud83d\udd14${this.name}, \u7ed3\u675f! \ud83d\udd5b ${s} \u79d2`),this.log(),(this.isSurge()||this.isQuanX()||this.isLoon())&&$done(t)}}(t,e)} \ No newline at end of file +function Env(t,e){class s{constructor(t){this.env=t}send(t,e="GET"){t="string"==typeof t?{url:t}:t;let s=this.get;return"POST"===e&&(s=this.post),new Promise((e,i)=>{s.call(this,t,(t,s,r)=>{t?i(t):e(s)})})}get(t){return this.send.call(this.env,t)}post(t){return this.send.call(this.env,t,"POST")}}return new class{constructor(t,e){this.name=t,this.http=new s(this),this.data=null,this.dataFile="box.dat",this.logs=[],this.isMute=!1,this.isNeedRewrite=!1,this.logSeparator="\n",this.startTime=(new Date).getTime(),Object.assign(this,e),this.log("",`\ud83d\udd14${this.name}, \u5f00\u59cb!`)}isNode(){return"undefined"!=typeof module&&!!module.exports}isQuanX(){return"undefined"!=typeof $task}isSurge(){return"undefined"!=typeof $httpClient&&"undefined"==typeof $loon}isLoon(){return"undefined"!=typeof $loon}toObj(t,e=null){try{return JSON.parse(t)}catch{return e}}toStr(t,e=null){try{return JSON.stringify(t)}catch{return e}}getjson(t,e){let s=e;const i=this.getdata(t);if(i)try{s=JSON.parse(this.getdata(t))}catch{}return s}setjson(t,e){try{return this.setdata(JSON.stringify(t),e)}catch{return!1}}getScript(t){return new Promise(e=>{this.get({url:t},(t,s,i)=>e(i))})}runScript(t,e){return new Promise(s=>{let i=this.getdata("@chavy_boxjs_userCfgs.httpapi");i=i?i.replace(/\n/g,"").trim():i;let r=this.getdata("@chavy_boxjs_userCfgs.httpapi_timeout");r=r?1*r:20,r=e&&e.timeout?e.timeout:r;const[o,h]=i.split("@"),a={url:`http://${h}/v1/scripting/evaluate`,body:{script_text:t,mock_type:"cron",timeout:r},headers:{"X-Key":o,Accept:"*/*"}};this.post(a,(t,e,i)=>s(i))}).catch(t=>this.logErr(t))}loaddata(){if(!this.isNode())return{};{this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(this.dataFile),e=this.path.resolve(process.cwd(),this.dataFile),s=this.fs.existsSync(t),i=!s&&this.fs.existsSync(e);if(!s&&!i)return{};{const i=s?t:e;try{return JSON.parse(this.fs.readFileSync(i))}catch(t){return{}}}}}writedata(){if(this.isNode()){this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(this.dataFile),e=this.path.resolve(process.cwd(),this.dataFile),s=this.fs.existsSync(t),i=!s&&this.fs.existsSync(e),r=JSON.stringify(this.data);s?this.fs.writeFileSync(t,r):i?this.fs.writeFileSync(e,r):this.fs.writeFileSync(t,r)}}lodash_get(t,e,s){const i=e.replace(/\[(\d+)\]/g,".$1").split(".");let r=t;for(const t of i)if(r=Object(r)[t],void 0===r)return s;return r}lodash_set(t,e,s){return Object(t)!==t?t:(Array.isArray(e)||(e=e.toString().match(/[^.[\]]+/g)||[]),e.slice(0,-1).reduce((t,s,i)=>Object(t[s])===t[s]?t[s]:t[s]=Math.abs(e[i+1])>>0==+e[i+1]?[]:{},t)[e[e.length-1]]=s,t)}getdata(t){let e=this.getval(t);if(/^@/.test(t)){const[,s,i]=/^@(.*?)\.(.*?)$/.exec(t),r=s?this.getval(s):"";if(r)try{const t=JSON.parse(r);e=t?this.lodash_get(t,i,""):e}catch(t){e=""}}return e}setdata(t,e){let s=!1;if(/^@/.test(e)){const[,i,r]=/^@(.*?)\.(.*?)$/.exec(e),o=this.getval(i),h=i?"null"===o?null:o||"{}":"{}";try{const e=JSON.parse(h);this.lodash_set(e,r,t),s=this.setval(JSON.stringify(e),i)}catch(e){const o={};this.lodash_set(o,r,t),s=this.setval(JSON.stringify(o),i)}}else s=this.setval(t,e);return s}getval(t){return this.isSurge()||this.isLoon()?$persistentStore.read(t):this.isQuanX()?$prefs.valueForKey(t):this.isNode()?(this.data=this.loaddata(),this.data[t]):this.data&&this.data[t]||null}setval(t,e){return this.isSurge()||this.isLoon()?$persistentStore.write(t,e):this.isQuanX()?$prefs.setValueForKey(t,e):this.isNode()?(this.data=this.loaddata(),this.data[e]=t,this.writedata(),!0):this.data&&this.data[e]||null}initGotEnv(t){this.got=this.got?this.got:require("got"),this.cktough=this.cktough?this.cktough:require("tough-cookie"),this.ckjar=this.ckjar?this.ckjar:new this.cktough.CookieJar,t&&(t.headers=t.headers?t.headers:{},void 0===t.headers.Cookie&&void 0===t.cookieJar&&(t.cookieJar=this.ckjar))}get(t,e=(()=>{})){t.headers&&(delete t.headers["Content-Type"],delete t.headers["Content-Length"]),this.isSurge()||this.isLoon()?(this.isSurge()&&this.isNeedRewrite&&(t.headers=t.headers||{},Object.assign(t.headers,{"X-Surge-Skip-Scripting":!1})),$httpClient.get(t,(t,s,i)=>{!t&&s&&(s.body=i,s.statusCode=s.status),e(t,s,i)})):this.isQuanX()?(this.isNeedRewrite&&(t.opts=t.opts||{},Object.assign(t.opts,{hints:!1})),$task.fetch(t).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>e(t))):this.isNode()&&(this.initGotEnv(t),this.got(t).on("redirect",(t,e)=>{try{if(t.headers["set-cookie"]){const s=t.headers["set-cookie"].map(this.cktough.Cookie.parse).toString();this.ckjar.setCookieSync(s,null),e.cookieJar=this.ckjar}}catch(t){this.logErr(t)}}).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>{const{message:s,response:i}=t;e(s,i,i&&i.body)}))}post(t,e=(()=>{})){if(t.body&&t.headers&&!t.headers["Content-Type"]&&(t.headers["Content-Type"]="application/x-www-form-urlencoded"),t.headers&&delete t.headers["Content-Length"],this.isSurge()||this.isLoon())this.isSurge()&&this.isNeedRewrite&&(t.headers=t.headers||{},Object.assign(t.headers,{"X-Surge-Skip-Scripting":!1})),$httpClient.post(t,(t,s,i)=>{!t&&s&&(s.body=i,s.statusCode=s.status),e(t,s,i)});else if(this.isQuanX())t.method="POST",this.isNeedRewrite&&(t.opts=t.opts||{},Object.assign(t.opts,{hints:!1})),$task.fetch(t).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>e(t));else if(this.isNode()){this.initGotEnv(t);const{url:s,...i}=t;this.got.post(s,i).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>{const{message:s,response:i}=t;e(s,i,i&&i.body)})}}time(t){let e={"M+":(new Date).getMonth()+1,"d+":(new Date).getDate(),"H+":(new Date).getHours(),"m+":(new Date).getMinutes(),"s+":(new Date).getSeconds(),"q+":Math.floor(((new Date).getMonth()+3)/3),S:(new Date).getMilliseconds()};/(y+)/.test(t)&&(t=t.replace(RegExp.$1,((new Date).getFullYear()+"").substr(4-RegExp.$1.length)));for(let s in e)new RegExp("("+s+")").test(t)&&(t=t.replace(RegExp.$1,1==RegExp.$1.length?e[s]:("00"+e[s]).substr((""+e[s]).length)));return t}msg(e=t,s="",i="",r){const o=t=>{if(!t)return t;if("string"==typeof t)return this.isLoon()?t:this.isQuanX()?{"open-url":t}:this.isSurge()?{url:t}:void 0;if("object"==typeof t){if(this.isLoon()){let e=t.openUrl||t.url||t["open-url"],s=t.mediaUrl||t["media-url"];return{openUrl:e,mediaUrl:s}}if(this.isQuanX()){let e=t["open-url"]||t.url||t.openUrl,s=t["media-url"]||t.mediaUrl;return{"open-url":e,"media-url":s}}if(this.isSurge()){let e=t.url||t.openUrl||t["open-url"];return{url:e}}}};this.isMute||(this.isSurge()||this.isLoon()?$notification.post(e,s,i,o(r)):this.isQuanX()&&$notify(e,s,i,o(r)));let h=["","==============\ud83d\udce3\u7cfb\u7edf\u901a\u77e5\ud83d\udce3=============="];h.push(e),s&&h.push(s),i&&h.push(i),console.log(h.join("\n")),this.logs=this.logs.concat(h)}log(...t){t.length>0&&(this.logs=[...this.logs,...t]),console.log(t.join(this.logSeparator))}logErr(t,e){const s=!this.isSurge()&&!this.isQuanX()&&!this.isLoon();s?this.log("",`\u2757\ufe0f${this.name}, \u9519\u8bef!`,t.stack):this.log("",`\u2757\ufe0f${this.name}, \u9519\u8bef!`,t)}wait(t){return new Promise(e=>setTimeout(e,t))}done(t={}){const e=(new Date).getTime(),s=(e-this.startTime)/1e3;this.log("",`\ud83d\udd14${this.name}, \u7ed3\u675f! \ud83d\udd5b ${s} \u79d2`),this.log(),(this.isSurge()||this.isQuanX()||this.isLoon())&&$done(t)}}(t,e)} diff --git a/Task/txnews2.js b/Task/txnews2.js deleted file mode 100644 index b2bc627025..0000000000 --- a/Task/txnews2.js +++ /dev/null @@ -1,286 +0,0 @@ -/* -更新时间: 2020-09-10 13:30 - -腾讯新闻签到修改版,可以自动阅读文章获取红包,该活动为瓜分百万现金挑战赛,针对幸运用户参与 - -获取Cookie方法: -1.把以下配置复制到响应配置下 -2.打开腾讯新闻app,阅读几篇文章,倒计时结束后即可获取阅读Cookie; -3.看一次推荐视频获取视频地址 -4.可能腾讯有某些限制,有些号码无法领取红包,手动阅读几篇,能领取红包,一般情况下都是正常的, -5.此脚本根据阅读篇数开启通知,默认阅读50篇通知一次,此版本不支持Boxjs ‼️ -版本更新日志: -1.01 修复无法自动获取视频红包,修改通知为阅读篇数间隔,即阅读篇数除以间隔余0时通知,或者自定义常开或常关, -1.02 增加通知跳转链接https://news.qq.com/FERD/cjRedDown.htm,需手动领取此红包 ---------------------- -Surge 4.0 -[Script] -腾讯新闻 = type=cron,cronexp=0 8 0 * * *,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/txnews2.js,script-update-interval=0 - -腾讯新闻 = type=http-request,pattern=https:\/\/api\.inews\.qq\.com\/event\/v1\/user\/event\/report\?,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/txnews2.js, requires-body=true - -~~~~~~~~~~~~~~~~~~~~~ -Loon 2.1.0+ -[Script] -# 本地脚本 -cron "04 00 * * *" script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/txnews2.js, enabled=true, tag=腾讯新闻 - -http-request https:\/\/api\.inews\.qq\.com\/event\/v1\/user\/event\/report\? script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/txnews2.js, requires-body=true - ------------------ - -QX 1.0.7+ : - [task_local] -0 9 * * * https://raw.githubusercontent.com/Sunert/Scripts/master/Task/txnews2.js, tag=腾讯新闻 - [rewrite_local] -https:\/\/api\.inews\.qq\.com\/event\/v1\/user\/event\/report\? url script-request-body https://raw.githubusercontent.com/Sunert/Scripts/master/Task/txnews2.js - -~~~~~~~~~~~~~~~~~~ - [MITM] -hostname = api.inews.qq.com - ---------------------------- - -Cookie获取后,请注释掉Cookie地址。 - -*/ -const cookieName = '腾讯新闻'; -let s = 500 // 间隔延迟时间 -const $ = new Env(cookieName); -let notifyInterval =$.getdata('notifynum')||50; //阅读篇数间隔通知开为1,常关为0; - -const signurlVal = $.getdata('sy_signurl_txnews2') -const cookieVal = $.getdata( 'sy_cookie_txnews2') -const videoVal = $.getdata( 'video_txnews2') - -let isGetCookie = typeof $request !== 'undefined' -if (isGetCookie) { - GetCookie() -} else { - -!(async () => { -{ -if(signurlVal){ - ID = signurlVal.match(/devid=[a-zA-Z0-9_-]+/g) -} -$.log("\n开始获取您的活动ID") - await getsign(); - await activity(); - await toRead(); - await lookVideo(); - await StepsTotal(); -if(getreadred > 0){ - redbody = `redpack_type=article&activity_id=${actid}` - await Redpack() -}; -if(getvideored>0){ -redbody = `redpack_type=video&activity_id=${actid}` - await Redpack() -}; - await getTotal(); - await showmsg() - } -})() - .catch((e) => $.logErr(e)) - .finally(() => $.done()) -} - -function GetCookie() { -if ($request &&$request.body.indexOf("article_read")> -1) { - const signurlVal = $request.url - const cookieVal = $request.headers['Cookie']; - $.log(`signurlVal:${signurlVal}`) - $.log(`cookieVal:${cookieVal}`) - if (signurlVal) $.setdata(signurlVal, 'sy_signurl_txnews2') - if (cookieVal) $.setdata(cookieVal, 'sy_cookie_txnews2') - $.msg(cookieName, `获取Cookie: 成功🎉`, ``) - } -if ($request &&$request.body.indexOf("video_read")> -1) { - const videoVal = $request.url - $.log(`videoVal:${videoVal}`) - if (videoVal) $.setdata(videoVal, 'video_txnews2') - $.msg(cookieName, `获取视频地址: 成功🎉`, ``) - } - } - - -//签到 -function getsign() { - return new Promise((resolve, reject) => { - const llUrl = { - url: `https://api.inews.qq.com/task/v1/user/signin/add?`,headers:{Cookie: cookieVal} - }; - $.post(llUrl, (error, response, data) => { - const obj = JSON.parse(data) - if (obj.info=="success"){ - next = obj.data.next_points - tip = obj.data.tip_soup||obj.data.share_tip - imgurl= obj.data.share_img - Dictum = tip.replace(/[\<|\.|\>|br]/g,"")+""+obj.data.author.replace(/[\<|\.|\>|br|图|腾讯网友]/g,"") - signinfo = '【签到信息】连续签到' + obj.data.signin_days+'天 '+'明日+'+ next +'金币 成功🎉\n'} - else { - $.msg('签到失败,🉐登录腾讯新闻app获取cookie', "", "") - console.log('签到失败,🉐登录腾讯新闻app获取cookie'+data) - return - } - resolve() - }) - }) -} - -function activity() { - return new Promise((resolve, reject) => { - setTimeout(()=>{ - const actUrl = { - url: `https://api.inews.qq.com/activity/v1/user/activity/get?isJailbreak=0&${ID}`, - headers: {Cookie: cookieVal}}; - $.get(actUrl, function(error,response, data) { - if (error) { - $.msg("获取活动Id失败‼️", "", error) - } else { - const obj = JSON.parse(data) - actid = obj.data.activity.id - console.log(` 您的活动ID为: `+actid+"\n") - } - resolve() - }) - },s) - }) - } - -//阅读阶梯 -function toRead() { - return new Promise((resolve, reject) => { - setTimeout(()=>{ - $.post({url: signurlVal, headers: {Cookie:cookieVal},body: 'event=article_read'},(error, resp, data)=> { - $.log("正在阅读文章\n") - }) - resolve() - },s) - }) -} -function lookVideo() { - return new Promise((resolve, reject) => { - setTimeout(()=>{ - $.post({url: videoVal, headers: {Cookie:cookieVal},body: 'event=video_read'},(error, response, data) =>{ - if (error){ - $.msg(cookieName, '观看视频:'+ error) - }else{ - $.log("正在浏览视频\n") - tolookresult = JSON.parse(data) - } - resolve() - }) - },s*2) - }) -} - -//阅读文章统计 -function StepsTotal() { -return new Promise((resolve, reject) => { - setTimeout(()=>{ - const StepsUrl = { - url: `https://api.inews.qq.com/activity/v1/activity/info/get?activity_id=${actid}&${ID}`, - headers: {Cookie: cookieVal} - } - $.get(StepsUrl, (error, response, data) => { - totalred = JSON.parse(data) - $.log("正在统计阅读数据:") - totalcion = totalred.data.extends.today_total_coin - if (totalred.ret == 0){ - for (i=0;i { - setTimeout(()=>{ - const cashUrl = { - url: `https://api.inews.qq.com/activity/v1/activity/redpack/get?isJailbreak=0&${ID}`, - headers: {Cookie: cookieVal}, - body: redbody - } - $.post(cashUrl, (error, response, data) => { - let rcash = JSON.parse(data) - try{ - redpacks = rcash.data.award.num/100 - if (rcash.ret == 0&&readredpack!=0&&getreadred>0){ - redpackres = `【阅读红包】到账`+readredpack+`元 🌷\n` - $.log("阅读红包到账"+readredpack+"元\n") - } - else if (rcash.ret == 0&&videoredpack!=0&&getvideored>0){ - redpackres = `【视频红包】到账`+videoredpack+`元 🌷\n` - $.log("视频红包到账"+videoredpack+"元\n") - } - } - catch(err){ - $.log("打开红包失败,响应数据: "+ data+"\n错误代码:"+err) - } - - resolve() - }) - },s) - }) -} - - -//收益总计 -function getTotal() { -return new Promise((resolve, reject) => { - const totalUrl = { - url: `https://api.inews.qq.com/activity/v1/usercenter/activity/list?isJailbreak`, - headers: {Cookie: cookieVal}}; - $.post(totalUrl, function(error,response, data) { - if (error) { - $.msg("获取收益信息失败‼️", "", error) - } else { - const obj = JSON.parse(data) - subTile = '【收益总计】'+obj.data.wealth[0].title +'金币 '+"钱包: " +obj.data.wealth[1].title+'元' - $.log("钱包收益共计"+obj.data.wealth[1].title+"元") - } - resolve() - }) - }) - } - -function showmsg() { - return new Promise((resolve, reject) => { - if(readnum||videonum){ - detail = signinfo + `【文章阅读】已读/再读: `+ readnum +`/`+readtitle+` 篇\n`+`【阅读红包】已开/总计: `+openreadred+`/`+readredtotal+` 个🧧\n`+ `【观看视频】已看/再看: `+ videonum +`/`+videotitle+` 分钟\n`+`【视频红包】已开/总计: `+openvideored+`/`+videoredtotal+` 个🧧\n【每日一句】`+Dictum - } - if -(readnum%notifyInterval==0){ - $.msg(cookieName,subTile,detail,{ 'open-url': "https://news.qq.com/FERD/cjRedDown.htm", 'media-url': imgurl } ) - } - else if (openreadred==readredtotal&&openvideored==videoredtotal){ - $.msg(cookieName+` 今日任务已完成✅`,subTile,detail,{ 'open-url': "https://news.qq.com/FERD/cjRedDown.htm", 'media-url': imgurl } ) - } - resolve() - }) -} - -// prettier-ignore -function Env(t,e){class s{constructor(t){this.env=t}send(t,e="GET"){t="string"==typeof t?{url:t}:t;let s=this.get;return"POST"===e&&(s=this.post),new Promise((e,i)=>{s.call(this,t,(t,s,r)=>{t?i(t):e(s)})})}get(t){return this.send.call(this.env,t)}post(t){return this.send.call(this.env,t,"POST")}}return new class{constructor(t,e){this.name=t,this.http=new s(this),this.data=null,this.dataFile="box.dat",this.logs=[],this.isMute=!1,this.isNeedRewrite=!1,this.logSeparator="\n",this.startTime=(new Date).getTime(),Object.assign(this,e),this.log("",`\ud83d\udd14${this.name}, \u5f00\u59cb!`)}isNode(){return"undefined"!=typeof module&&!!module.exports}isQuanX(){return"undefined"!=typeof $task}isSurge(){return"undefined"!=typeof $httpClient&&"undefined"==typeof $loon}isLoon(){return"undefined"!=typeof $loon}toObj(t,e=null){try{return JSON.parse(t)}catch{return e}}toStr(t,e=null){try{return JSON.stringify(t)}catch{return e}}getjson(t,e){let s=e;const i=this.getdata(t);if(i)try{s=JSON.parse(this.getdata(t))}catch{}return s}setjson(t,e){try{return this.setdata(JSON.stringify(t),e)}catch{return!1}}getScript(t){return new Promise(e=>{this.get({url:t},(t,s,i)=>e(i))})}runScript(t,e){return new Promise(s=>{let i=this.getdata("@chavy_boxjs_userCfgs.httpapi");i=i?i.replace(/\n/g,"").trim():i;let r=this.getdata("@chavy_boxjs_userCfgs.httpapi_timeout");r=r?1*r:20,r=e&&e.timeout?e.timeout:r;const[o,h]=i.split("@"),a={url:`http://${h}/v1/scripting/evaluate`,body:{script_text:t,mock_type:"cron",timeout:r},headers:{"X-Key":o,Accept:"*/*"}};this.post(a,(t,e,i)=>s(i))}).catch(t=>this.logErr(t))}loaddata(){if(!this.isNode())return{};{this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(this.dataFile),e=this.path.resolve(process.cwd(),this.dataFile),s=this.fs.existsSync(t),i=!s&&this.fs.existsSync(e);if(!s&&!i)return{};{const i=s?t:e;try{return JSON.parse(this.fs.readFileSync(i))}catch(t){return{}}}}}writedata(){if(this.isNode()){this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(this.dataFile),e=this.path.resolve(process.cwd(),this.dataFile),s=this.fs.existsSync(t),i=!s&&this.fs.existsSync(e),r=JSON.stringify(this.data);s?this.fs.writeFileSync(t,r):i?this.fs.writeFileSync(e,r):this.fs.writeFileSync(t,r)}}lodash_get(t,e,s){const i=e.replace(/\[(\d+)\]/g,".$1").split(".");let r=t;for(const t of i)if(r=Object(r)[t],void 0===r)return s;return r}lodash_set(t,e,s){return Object(t)!==t?t:(Array.isArray(e)||(e=e.toString().match(/[^.[\]]+/g)||[]),e.slice(0,-1).reduce((t,s,i)=>Object(t[s])===t[s]?t[s]:t[s]=Math.abs(e[i+1])>>0==+e[i+1]?[]:{},t)[e[e.length-1]]=s,t)}getdata(t){let e=this.getval(t);if(/^@/.test(t)){const[,s,i]=/^@(.*?)\.(.*?)$/.exec(t),r=s?this.getval(s):"";if(r)try{const t=JSON.parse(r);e=t?this.lodash_get(t,i,""):e}catch(t){e=""}}return e}setdata(t,e){let s=!1;if(/^@/.test(e)){const[,i,r]=/^@(.*?)\.(.*?)$/.exec(e),o=this.getval(i),h=i?"null"===o?null:o||"{}":"{}";try{const e=JSON.parse(h);this.lodash_set(e,r,t),s=this.setval(JSON.stringify(e),i)}catch(e){const o={};this.lodash_set(o,r,t),s=this.setval(JSON.stringify(o),i)}}else s=this.setval(t,e);return s}getval(t){return this.isSurge()||this.isLoon()?$persistentStore.read(t):this.isQuanX()?$prefs.valueForKey(t):this.isNode()?(this.data=this.loaddata(),this.data[t]):this.data&&this.data[t]||null}setval(t,e){return this.isSurge()||this.isLoon()?$persistentStore.write(t,e):this.isQuanX()?$prefs.setValueForKey(t,e):this.isNode()?(this.data=this.loaddata(),this.data[e]=t,this.writedata(),!0):this.data&&this.data[e]||null}initGotEnv(t){this.got=this.got?this.got:require("got"),this.cktough=this.cktough?this.cktough:require("tough-cookie"),this.ckjar=this.ckjar?this.ckjar:new this.cktough.CookieJar,t&&(t.headers=t.headers?t.headers:{},void 0===t.headers.Cookie&&void 0===t.cookieJar&&(t.cookieJar=this.ckjar))}get(t,e=(()=>{})){t.headers&&(delete t.headers["Content-Type"],delete t.headers["Content-Length"]),this.isSurge()||this.isLoon()?(this.isSurge()&&this.isNeedRewrite&&(t.headers=t.headers||{},Object.assign(t.headers,{"X-Surge-Skip-Scripting":!1})),$httpClient.get(t,(t,s,i)=>{!t&&s&&(s.body=i,s.statusCode=s.status),e(t,s,i)})):this.isQuanX()?(this.isNeedRewrite&&(t.opts=t.opts||{},Object.assign(t.opts,{hints:!1})),$task.fetch(t).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>e(t))):this.isNode()&&(this.initGotEnv(t),this.got(t).on("redirect",(t,e)=>{try{const s=t.headers["set-cookie"].map(this.cktough.Cookie.parse).toString();this.ckjar.setCookieSync(s,null),e.cookieJar=this.ckjar}catch(t){this.logErr(t)}}).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>{const{message:s,response:i}=t;e(s,i,i&&i.body)}))}post(t,e=(()=>{})){if(t.body&&t.headers&&!t.headers["Content-Type"]&&(t.headers["Content-Type"]="application/x-www-form-urlencoded"),t.headers&&delete t.headers["Content-Length"],this.isSurge()||this.isLoon())this.isSurge()&&this.isNeedRewrite&&(t.headers=t.headers||{},Object.assign(t.headers,{"X-Surge-Skip-Scripting":!1})),$httpClient.post(t,(t,s,i)=>{!t&&s&&(s.body=i,s.statusCode=s.status),e(t,s,i)});else if(this.isQuanX())t.method="POST",this.isNeedRewrite&&(t.opts=t.opts||{},Object.assign(t.opts,{hints:!1})),$task.fetch(t).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>e(t));else if(this.isNode()){this.initGotEnv(t);const{url:s,...i}=t;this.got.post(s,i).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>{const{message:s,response:i}=t;e(s,i,i&&i.body)})}}time(t){let e={"M+":(new Date).getMonth()+1,"d+":(new Date).getDate(),"H+":(new Date).getHours(),"m+":(new Date).getMinutes(),"s+":(new Date).getSeconds(),"q+":Math.floor(((new Date).getMonth()+3)/3),S:(new Date).getMilliseconds()};/(y+)/.test(t)&&(t=t.replace(RegExp.$1,((new Date).getFullYear()+"").substr(4-RegExp.$1.length)));for(let s in e)new RegExp("("+s+")").test(t)&&(t=t.replace(RegExp.$1,1==RegExp.$1.length?e[s]:("00"+e[s]).substr((""+e[s]).length)));return t}msg(e=t,s="",i="",r){const o=t=>{if(!t||!this.isLoon()&&this.isSurge())return t;if("string"==typeof t)return this.isLoon()?t:this.isQuanX()?{"open-url":t}:void 0;if("object"==typeof t){if(this.isLoon()){let e=t.openUrl||t["open-url"],s=t.mediaUrl||t["media-url"];return{openUrl:e,mediaUrl:s}}if(this.isQuanX()){let e=t["open-url"]||t.openUrl,s=t["media-url"]||t.mediaUrl;return{"open-url":e,"media-url":s}}}};this.isMute||(this.isSurge()||this.isLoon()?$notification.post(e,s,i,o(r)):this.isQuanX()&&$notify(e,s,i,o(r)));let h=["","==============\ud83d\udce3\u7cfb\u7edf\u901a\u77e5\ud83d\udce3=============="];h.push(e),s&&h.push(s),i&&h.push(i),console.log(h.join("\n")),this.logs=this.logs.concat(h)}log(...t){t.length>0&&(this.logs=[...this.logs,...t]),console.log(t.join(this.logSeparator))}logErr(t,e){const s=!this.isSurge()&&!this.isQuanX()&&!this.isLoon();s?this.log("",`\u2757\ufe0f${this.name}, \u9519\u8bef!`,t.stack):this.log("",`\u2757\ufe0f${this.name}, \u9519\u8bef!`,t)}wait(t){return new Promise(e=>setTimeout(e,t))}done(t={}){const e=(new Date).getTime(),s=(e-this.startTime)/1e3;this.log("",`\ud83d\udd14${this.name}, \u7ed3\u675f! \ud83d\udd5b ${s} \u79d2`),this.log(),(this.isSurge()||this.isQuanX()||this.isLoon())&&$done(t)}}(t,e)} diff --git a/Task/txnews_task.js b/Task/txnews_task.js new file mode 100644 index 0000000000..9e4767c20c --- /dev/null +++ b/Task/txnews_task.js @@ -0,0 +1,106 @@ +/* +更新时间: 2021-01-23 07:46 + +Github Actions使用方法见[@lxk0301](https://raw.githubusercontent.com/lxk0301/scripts/master/githubAction.md) 使用方法大同小异 + +获取secrects方法和腾讯新闻签到任务相同,TX_CK即腾讯新闻Cookie,TX_READ即sy_signurl_txnews阅读任务地址,TX_VIDEO即video_txnews视频地址;其中TX_CK只能填一个账号secrects,其他链接地址可用#或换行隔开,多账号任务链接不可共用阅读和视频地址‼️ +拷贝抓包的请求体到下面Value的文本框中,本脚本不包含任何推送通知 + +*/ + +const $ = new Env("腾讯新闻阅读") + +let RdArr = [], VdArr = []; + if (process.env.TX_READ && process.env.TX_READ.indexOf('#') > -1) { + RdUrl = process.env.TX_READ.split('#'); + console.log(`您选择的是用"#"隔开\n`) + } + else if (process.env.TX_READ && process.env.TX_READ.indexOf('\n') > -1) { + RdUrl = process.env.TX_READ.split('\n'); + console.log(`您选择的是用换行隔开\n`) + } else { + RdUrl = process.env.TX_READ + } + if (process.env.TX_VIDEO && process.env.TX_VIDEO.indexOf('#') > -1) { + VdUrl = process.env.TX_VIDEO.split('#'); + console.log(`您选择的是用"#"隔开\n`) + } + else if (process.env.TX_VIDEO && process.env.TX_VIDEO.indexOf('\n') > -1) { + VdUrl = process.env.TX_VIDEO.split('\n'); + console.log(`您选择的是用换行隔开\n`) + } else { + VdUrl = process.env.TX_VIDEO + } + Object.keys(RdUrl).forEach((item) => { + if (RdUrl[item]) { + RdArr.push(RdUrl[item]) + } + }) + Object.keys(VdUrl).forEach((item) => { + if (VdUrl[item]) { + VdArr.push(VdUrl[item]) + } + }) + console.log(`============ 脚本执行-国际标准时间(UTC):${new Date().toLocaleString()} =============\n`) + console.log(`============ 脚本执行-北京时间(UTC+8):${new Date(new Date().getTime() + 8 * 60 * 60 * 1000).toLocaleString()} =============\n`) + +!(async () => { + if (process.env.TX_CK){ + Cookieval = process.env.TX_CK + } + if (!Cookieval && (!RdArr || !VdUrl)) { + console.log($.name, '【提示】请把腾讯Ck和任务链接填入Github 的 Secrets 中,请以#或者换行隔开') + return; + } + if(RdArr){ + console.log("共"+RdArr.length+"次阅读任务") + for (let i = 0; i < RdArr.length; i++) { + TaskUrl = RdArr[i]; + body = "event=article_read" + $.index = i + 1; + console.log(`-------------------------\n\n开始腾讯新闻第${$.index}次阅读`) + await AutoRead(); + console.log(`请等待5s后继续阅读第${$.index+1}次任务`) + await $.wait(5000); + } + console.log(`-------------------------\n\n腾讯新闻共完成阅读任务(${$.index})次,阅读金币详情见App,阅读任务全部结束`) + } + if(VdArr){ + console.log("共"+VdArr.length+"次视频任务") + for (var j = 0; j < VdArr.length; j++) { + + TaskUrl = VdArr[j]; + body = "event=video_read" + $.vdindex = j + 1; + console.log(`-------------------------\n\n开始腾讯新闻第${$.vdindex}次看视频`) + await AutoRead(); + console.log(`请等待10s后继续视频第${$.vdindex+1}次任务`) + await $.wait(10000); + } + console.log(`-------------------------\n\n共完成视频任务(${$.vdindex})次,视频金币详情见App,视频任务全部结束`) +} +})() + .catch((e) => $.logErr(e)) + .finally(() => $.done()) + +function AutoRead(){ + return new Promise((resolve, reject) => { + $.post({url: TaskUrl, + headers: {Cookie:Cookieval}, + body: body},(error, resp, data)=> { + try{ + let obj = JSON.parse(data) + if(obj.ret == 0){ + console.log("本次阅读成功,获取收益" +obj.data.countdown_timer.countdown_tips+"\n") + } else if(body.indexOf("article")>-1){console.log("本次阅读文章失败," +obj.info+"\n") + }else if(body.indexOf("video")>-1){console.log("本次观看视频失败," +obj.info+"\n") + } + } catch(error){ + console.log("本次阅读失败"+data+"\n") + } + resolve() + }) + }) +} + +function Env(t,e){class s{constructor(t){this.env=t}send(t,e="GET"){t="string"==typeof t?{url:t}:t;let s=this.get;return"POST"===e&&(s=this.post),new Promise((e,i)=>{s.call(this,t,(t,s,r)=>{t?i(t):e(s)})})}get(t){return this.send.call(this.env,t)}post(t){return this.send.call(this.env,t,"POST")}}return new class{constructor(t,e){this.name=t,this.http=new s(this),this.data=null,this.dataFile="box.dat",this.logs=[],this.isMute=!1,this.isNeedRewrite=!1,this.logSeparator="\n",this.startTime=(new Date).getTime(),Object.assign(this,e),this.log("",`\ud83d\udd14${this.name}, \u5f00\u59cb!`)}isNode(){return"undefined"!=typeof module&&!!module.exports}isQuanX(){return"undefined"!=typeof $task}isSurge(){return"undefined"!=typeof $httpClient&&"undefined"==typeof $loon}isLoon(){return"undefined"!=typeof $loon}toObj(t,e=null){try{return JSON.parse(t)}catch{return e}}toStr(t,e=null){try{return JSON.stringify(t)}catch{return e}}getjson(t,e){let s=e;const i=this.getdata(t);if(i)try{s=JSON.parse(this.getdata(t))}catch{}return s}setjson(t,e){try{return this.setdata(JSON.stringify(t),e)}catch{return!1}}getScript(t){return new Promise(e=>{this.get({url:t},(t,s,i)=>e(i))})}runScript(t,e){return new Promise(s=>{let i=this.getdata("@chavy_boxjs_userCfgs.httpapi");i=i?i.replace(/\n/g,"").trim():i;let r=this.getdata("@chavy_boxjs_userCfgs.httpapi_timeout");r=r?1*r:20,r=e&&e.timeout?e.timeout:r;const[o,h]=i.split("@"),a={url:`http://${h}/v1/scripting/evaluate`,body:{script_text:t,mock_type:"cron",timeout:r},headers:{"X-Key":o,Accept:"*/*"}};this.post(a,(t,e,i)=>s(i))}).catch(t=>this.logErr(t))}loaddata(){if(!this.isNode())return{};{this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(this.dataFile),e=this.path.resolve(process.cwd(),this.dataFile),s=this.fs.existsSync(t),i=!s&&this.fs.existsSync(e);if(!s&&!i)return{};{const i=s?t:e;try{return JSON.parse(this.fs.readFileSync(i))}catch(t){return{}}}}}writedata(){if(this.isNode()){this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(this.dataFile),e=this.path.resolve(process.cwd(),this.dataFile),s=this.fs.existsSync(t),i=!s&&this.fs.existsSync(e),r=JSON.stringify(this.data);s?this.fs.writeFileSync(t,r):i?this.fs.writeFileSync(e,r):this.fs.writeFileSync(t,r)}}lodash_get(t,e,s){const i=e.replace(/\[(\d+)\]/g,".$1").split(".");let r=t;for(const t of i)if(r=Object(r)[t],void 0===r)return s;return r}lodash_set(t,e,s){return Object(t)!==t?t:(Array.isArray(e)||(e=e.toString().match(/[^.[\]]+/g)||[]),e.slice(0,-1).reduce((t,s,i)=>Object(t[s])===t[s]?t[s]:t[s]=Math.abs(e[i+1])>>0==+e[i+1]?[]:{},t)[e[e.length-1]]=s,t)}getdata(t){let e=this.getval(t);if(/^@/.test(t)){const[,s,i]=/^@(.*?)\.(.*?)$/.exec(t),r=s?this.getval(s):"";if(r)try{const t=JSON.parse(r);e=t?this.lodash_get(t,i,""):e}catch(t){e=""}}return e}setdata(t,e){let s=!1;if(/^@/.test(e)){const[,i,r]=/^@(.*?)\.(.*?)$/.exec(e),o=this.getval(i),h=i?"null"===o?null:o||"{}":"{}";try{const e=JSON.parse(h);this.lodash_set(e,r,t),s=this.setval(JSON.stringify(e),i)}catch(e){const o={};this.lodash_set(o,r,t),s=this.setval(JSON.stringify(o),i)}}else s=this.setval(t,e);return s}getval(t){return this.isSurge()||this.isLoon()?$persistentStore.read(t):this.isQuanX()?$prefs.valueForKey(t):this.isNode()?(this.data=this.loaddata(),this.data[t]):this.data&&this.data[t]||null}setval(t,e){return this.isSurge()||this.isLoon()?$persistentStore.write(t,e):this.isQuanX()?$prefs.setValueForKey(t,e):this.isNode()?(this.data=this.loaddata(),this.data[e]=t,this.writedata(),!0):this.data&&this.data[e]||null}initGotEnv(t){this.got=this.got?this.got:require("got"),this.cktough=this.cktough?this.cktough:require("tough-cookie"),this.ckjar=this.ckjar?this.ckjar:new this.cktough.CookieJar,t&&(t.headers=t.headers?t.headers:{},void 0===t.headers.Cookie&&void 0===t.cookieJar&&(t.cookieJar=this.ckjar))}get(t,e=(()=>{})){t.headers&&(delete t.headers["Content-Type"],delete t.headers["Content-Length"]),this.isSurge()||this.isLoon()?(this.isSurge()&&this.isNeedRewrite&&(t.headers=t.headers||{},Object.assign(t.headers,{"X-Surge-Skip-Scripting":!1})),$httpClient.get(t,(t,s,i)=>{!t&&s&&(s.body=i,s.statusCode=s.status),e(t,s,i)})):this.isQuanX()?(this.isNeedRewrite&&(t.opts=t.opts||{},Object.assign(t.opts,{hints:!1})),$task.fetch(t).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>e(t))):this.isNode()&&(this.initGotEnv(t),this.got(t).on("redirect",(t,e)=>{try{if(t.headers["set-cookie"]){const s=t.headers["set-cookie"].map(this.cktough.Cookie.parse).toString();this.ckjar.setCookieSync(s,null),e.cookieJar=this.ckjar}}catch(t){this.logErr(t)}}).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>{const{message:s,response:i}=t;e(s,i,i&&i.body)}))}post(t,e=(()=>{})){if(t.body&&t.headers&&!t.headers["Content-Type"]&&(t.headers["Content-Type"]="application/x-www-form-urlencoded"),t.headers&&delete t.headers["Content-Length"],this.isSurge()||this.isLoon())this.isSurge()&&this.isNeedRewrite&&(t.headers=t.headers||{},Object.assign(t.headers,{"X-Surge-Skip-Scripting":!1})),$httpClient.post(t,(t,s,i)=>{!t&&s&&(s.body=i,s.statusCode=s.status),e(t,s,i)});else if(this.isQuanX())t.method="POST",this.isNeedRewrite&&(t.opts=t.opts||{},Object.assign(t.opts,{hints:!1})),$task.fetch(t).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>e(t));else if(this.isNode()){this.initGotEnv(t);const{url:s,...i}=t;this.got.post(s,i).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>{const{message:s,response:i}=t;e(s,i,i&&i.body)})}}time(t){let e={"M+":(new Date).getMonth()+1,"d+":(new Date).getDate(),"H+":(new Date).getHours(),"m+":(new Date).getMinutes(),"s+":(new Date).getSeconds(),"q+":Math.floor(((new Date).getMonth()+3)/3),S:(new Date).getMilliseconds()};/(y+)/.test(t)&&(t=t.replace(RegExp.$1,((new Date).getFullYear()+"").substr(4-RegExp.$1.length)));for(let s in e)new RegExp("("+s+")").test(t)&&(t=t.replace(RegExp.$1,1==RegExp.$1.length?e[s]:("00"+e[s]).substr((""+e[s]).length)));return t}msg(e=t,s="",i="",r){const o=t=>{if(!t)return t;if("string"==typeof t)return this.isLoon()?t:this.isQuanX()?{"open-url":t}:this.isSurge()?{url:t}:void 0;if("object"==typeof t){if(this.isLoon()){let e=t.openUrl||t.url||t["open-url"],s=t.mediaUrl||t["media-url"];return{openUrl:e,mediaUrl:s}}if(this.isQuanX()){let e=t["open-url"]||t.url||t.openUrl,s=t["media-url"]||t.mediaUrl;return{"open-url":e,"media-url":s}}if(this.isSurge()){let e=t.url||t.openUrl||t["open-url"];return{url:e}}}};this.isMute||(this.isSurge()||this.isLoon()?$notification.post(e,s,i,o(r)):this.isQuanX()&&$notify(e,s,i,o(r)));let h=["","==============\ud83d\udce3\u7cfb\u7edf\u901a\u77e5\ud83d\udce3=============="];h.push(e),s&&h.push(s),i&&h.push(i),console.log(h.join("\n")),this.logs=this.logs.concat(h)}log(...t){t.length>0&&(this.logs=[...this.logs,...t]),console.log(t.join(this.logSeparator))}logErr(t,e){const s=!this.isSurge()&&!this.isQuanX()&&!this.isLoon();s?this.log("",`\u2757\ufe0f${this.name}, \u9519\u8bef!`,t.stack):this.log("",`\u2757\ufe0f${this.name}, \u9519\u8bef!`,t)}wait(t){return new Promise(e=>setTimeout(e,t))}done(t={}){const e=(new Date).getTime(),s=(e-this.startTime)/1e3;this.log("",`\ud83d\udd14${this.name}, \u7ed3\u675f! \ud83d\udd5b ${s} \u79d2`),this.log(),(this.isSurge()||this.isQuanX()||this.isLoon())&&$done(t)}}(t,e)} diff --git a/Task/weather_pro.js b/Task/weather_pro.js deleted file mode 100644 index 7133c46a03..0000000000 --- a/Task/weather_pro.js +++ /dev/null @@ -1,847 +0,0 @@ -/* -可以自由定制显示的天气脚本,想怎样都随你,轻松修改轻松查看 -https://github.com/sazs34/TaskConfig/blob/master/assets/weather_pro.md - */ -let config = { - darksky_api: "填这里", //从https://darksky.net/dev/ 上申请key填入即可 - aqicn_api: "填这里", //从http://aqicn.org/data-platform/token/#/ 上申请key填入即可 - huweather_apiKey: "填这里", //和风天气APIkey,可自行前往 https://dev.heweather.com/ 进行获取 - lat_lon: "填这里", //请填写经纬度,直接从谷歌地图中获取即可 - lang: "zh", //语言,随意切换为您想要的语言哦(zh/zh-tw/ja/en/fr/...) - log: 0, //调试日志,0为不开启,1为开启,2为开启精简日志 - timeout: 0, //超时时间,单位毫秒(1000毫秒=1秒),一般不推荐修改[为0则不限制超时时间] - show: { - //普通每天的 - template: { - title: `$[city]$[district] $[summary]`, - subtitle: `$[weatherIcon]$[weather] $[temperatureMin] ~ $[temperatureMax]°C ☔️降雨概率 $[precipProbability]%`, - detail: `$[aqiIcon]空气质量 $[aqi]($[aqiDesc]) 🏋🏻‍♀️气压$[atmosphere]pa -🌪风速$[windSpeed]km/h 💨$[windDir]$[windPower]级 -👀紫外线指数 $[uv]($[uvDesc]) 💦湿度$[currentHumidity]% -🌡体感温度 $[apparentTemperatureMin] ~ $[apparentTemperatureMax]°C 🎚当前温度 $[currentTemperature]℃ -[生活指数] -$[lifeStyle($[icon]:$[brf],$[txt])] -[天气周报] $[weeklySummary] -$[daily($[month]月$[day]日 $[temperatureLow]~$[temperatureHigh]°C $[weatherIcon]$[weather])]` - }, - lifestyle: { //此处用于显示各项生活指数,可自行调整顺序,顺序越在前面则显示也会靠前,如果您不想查看某一指数,置为false即可,想看置为true即可 - drsg: true, //穿衣指数, - flu: true, //感冒指数, - comf: true, //舒适度指数, - cw: false, //洗车指数, - sport: false, //运动指数, - trav: false, //旅游指数, - uv: false, //紫外线指数, - air: false, //空气污染扩散条件指数, - ac: false, //空调开启指数, - ag: false, //过敏指数, - gl: false, //太阳镜指数, - mu: false, //化妆指数, - airc: false, //晾晒指数, - ptfc: true, //交通指数, - fsh: false, //钓鱼指数, - spi: false, //防晒指数 - } - } -} - -const provider = { - heweather_now: { - api: `https://free-api.heweather.net/s6/weather/now?location=${config.lat_lon.replace(/\s/g, "").replace(",", ",")}&key=${config.huweather_apiKey}`, - progress: 0, //处理进度:0需处理1已处理2无需处理9报错 - timeoutNumber: 0, //超时处理编号 - data: { - basic: {}, - now: {} - }, - support: ['$[province]', '$[city]', '$[district]', '$[weatherIcon]', '$[weather]', '$[currentTemperature]', '$[currentWindSpeed]', '$[currentWindDir]', '$[currentWindPower]', '$[currentHumidity]', '$[currentAtmosphere]', '$[currentVisibility]'] - }, - heweather_daily: { - api: `https://free-api.heweather.net/s6/weather/forecast?location=${config.lat_lon.replace(/\s/g, "").replace(",", ",")}&key=${config.huweather_apiKey}`, - progress: 0, - timeoutNumber: 0, - data: {}, - support: ['$[temperatureMin]', '$[temperatureMax]', '$[precipProbability]', '$[windSpeed]', '$[windDir]', '$[windPower]', '$[humidity]', '$[atmosphere]', '$[visibility]', '$[uv]', '$[uvDesc]', '$[sunrise]', '$[sunset]', '$[moonrise]', '$[moonset]'] - }, - heweather_air: { - api: `https://free-api.heweather.net/s6/air/now?location=auto_ip&key=${config.huweather_apiKey}`, - progress: 0, - timeoutNumber: 0, - data: {}, - support: [] - }, - heweather_lifestyle: { - api: `https://free-api.heweather.net/s6/weather/lifestyle?location=${config.lat_lon.replace(/\s/g, "").replace(",", ",")}&key=${config.huweather_apiKey}`, - progress: 0, - timeoutNumber: 0, - data: [], - support: ['$[lifeStyle]'] - }, - darksky: { - api: `https://api.darksky.net/forecast/${config.darksky_api}/${config.lat_lon.replace(/\s/g, "").replace(",", ",")}?lang=${config.lang}&units=si`, - progress: 0, - timeoutNumber: 0, - data: { - daily: { - data: [] - }, - hourly: { - data: [] - }, - currently: {} - }, - support: ['$[summary]', '$[weeklySummary]', '$[weatherIcon]', '$[weather]', '$[temperatureMin]', '$[temperatureMax]', '$[apparentTemperatureMin]', '$[apparentTemperatureMax]', '$[precipProbability]', '$[uv]', '$[uvDesc]'] - }, - aqicn: { - api: `https://api.waqi.info/feed/geo:${config.lat_lon.replace(/\s/g, "").replace(",", ",").replace(/,/, ";")}/?token=${config.aqicn_api}`, - progress: 0, - data: {}, - support: ['$[aqiIcon]', '$[aqi]', '$[aqiDesc]', '$[aqiWarning]'] - } -} -// #region 天气数据获取 -function weather() { - support(); - heweatherNow(); - heweatherDaily(); - darksky(); - aqicn(); - heweatherLifestyle(); -} -//clear-day, partly-cloudy-day, cloudy, clear-night, rain, snow, sleet, wind, fog, or partly-cloudy-night -//☀️🌤⛅️🌥☁️🌦🌧⛈🌩🌨❄️💧💦🌫☔️☂️ ☃️⛄️ -function darksky() { - if (provider.darksky.progress == 2) return; - start("darksky"); - $task.fetch({ - url: provider.darksky.api - }).then(response => { - try { - let darkObj = JSON.parse(response.body); - record(`天气数据获取-A1-${response.body}`); - if (darkObj.error) { - $notify("DarkApi", "出错啦", darkObj.error); - } - provider.darksky.data.daily = darkObj.daily; - provider.darksky.data.hourly = darkObj.hourly; - provider.darksky.data.currently = darkObj.currently; - record(`天气数据获取-A2`); - check('darksky', true) - } catch (e) { - console.log(`天气数据A获取报错${JSON.stringify(e)}`) - } - }, reason => { - record(`天气数据获取-A3-${reason.error}`); - check('darksky', false); - }); -} - -function aqicn() { - if (provider.aqicn.progress == 2) return; - start("aqicn"); - $task.fetch({ - url: provider.aqicn.api - }).then(response => { - try { - var waqiObj = JSON.parse(response.body); - if (waqiObj.status == 'error') { - $notify("Aqicn", "出错啦", waqiObj.data); - } else { - record(`天气数据获取-B1-${response.body}`); - provider.aqicn.data = { - ...getAqiInfo(waqiObj.data.aqi) - }; - } - check('aqicn', true) - } catch (e) { - console.log(`天气数据B获取报错${JSON.stringify(e)}`) - } - }, reason => { - record(`天气数据获取-B2-${reason.error}`); - //获取精确数据失败后,直接获取粗略信息即可 - heweatherAir(); - }); -} - -function heweatherNow() { - start("heweather_now"); - $task.fetch({ - url: provider.heweather_now.api - }).then(response => { - try { - record(`天气数据获取-C1-${response.body}`); - var heObj = JSON.parse(response.body); - provider.heweather_now.data.basic = heObj.HeWeather6[0].basic; - provider.heweather_now.data.now = heObj.HeWeather6[0].now; - check('heweather_now', true) - } catch (e) { - console.log(`天气数据C获取报错${JSON.stringify(e)}`) - } - }, reason => { - record(`天气数据获取-C2-${reason.error}`); - //因为此接口出错率还挺高的,所以即使报错我们也不处理,该返回什么就返回什么好了 - check('heweather_now', false) - }) -} - -function heweatherDaily() { - if (provider.heweather_daily.progress == 2) return; - start("heweather_daily"); - $task.fetch({ - url: provider.heweather_daily.api - }).then(response => { - try { - record(`天气数据获取-D1-${response.body}`); - var heObj = JSON.parse(response.body); - provider.heweather_daily.data = heObj.HeWeather6[0].daily_forecast[0]; - check('heweather_daily', true) - } catch (e) { - console.log(`天气数据D获取报错${JSON.stringify(e)}`) - } - }, reason => { - record(`天气数据获取-D2-${reason.error}`); - //因为此接口出错率还挺高的,所以即使报错我们也不处理,该返回什么就返回什么好了 - check('heweather_daily', false) - }) -} - -function heweatherAir() { - if (provider.heweather_air.progress == 2) return; - start("heweather_air"); - $task.fetch({ - url: provider.heweather_air.api - }).then(response => { - try { - record(`天气数据获取F1-${response.body}`); - var heObj = JSON.parse(response.body); - provider.heweather_air.data = { - ...getAqiInfo(heObj.HeWeather6[0].air_now_city.aqi) - }; - check('heweather_air', true) - } catch (e) { - console.log(`天气数据F获取报错${JSON.stringify(e)}`) - } - }, reason => { - record(`天气数据获取-F2-${reason.error}`); - //因为此接口出错率还挺高的,所以即使报错我们也不处理,该返回什么就返回什么好了 - check('heweather_air', false) - }) -} - -function heweatherLifestyle() { - if (provider.heweather_lifestyle.progress == 2) return; - start("heweather_lifestyle"); - var needRequest = false; - //判断一下是否全部都是false,全false的话,则不需要请求此接口直接返回渲染的数据了 - for (var item in config.show.lifestyle) { - if (config.show.lifestyle[item]) { - needRequest = true; - break; - } - } - if (needRequest) { - $task.fetch({ - url: provider.heweather_lifestyle.api - }).then(response => { - try { - record(`天气数据获取-E1-${response.body}`); - var heObj = JSON.parse(response.body); - provider.heweather_lifestyle.data = heObj.HeWeather6[0].lifestyle; - check('heweather_lifestyle', true) - } catch (e) { - console.log(`天气数据E获取报错${JSON.stringify(e)}`) - } - }, reason => { - record(`天气数据获取-E2-${reason.error}`); - //因为此接口出错率还挺高的,所以即使报错我们也不处理,该返回什么就返回什么好了 - check('heweather_lifestyle', false) - }) - } else { - check('heweather_lifestyle', false) - } -} -//#endregion - -// #region 提醒数据组装 -function check(type, result) { - record(`check-${type}-${result}`); - //支持setTimeout居然不支持clearTimeout,有点难受 - if (provider[type].progress == 1 || provider[type].progress == 9) return; - provider[type].progress = result ? 1 : 9; - var isAllChecked = provider.heweather_now.progress != 0 && provider.heweather_daily.progress && provider.darksky.progress != 0 && (provider.aqicn.progress != 0 || provider.heweather_air.progress != 0) && provider.heweather_lifestyle.progress != 0; - if (isAllChecked) { - record(`天气数据渲染中[template]`); - try { - renderTemplate(); - } catch (e) { - record(`天气渲染出错-${JSON.stringify(e)}`); - } - } -} - -var lineBreak = ` -`; - -function renderTemplate() { - execArrayTemplate(); - const map = { - //省 - province: provider.heweather_now.data.basic.admin_area, - //市 - city: provider.heweather_now.data.basic.parent_city, - //区 - district: provider.heweather_now.data.basic.location || "UNKNOW", - //全天气候变化概述 - summary: `${provider.darksky.data.hourly.summary||""}`, - //一周气候变化概述 - weeklySummary: `${provider.darksky.data.daily.summary||""}`, - //天气图标 - weatherIcon: `${getHeweatherIcon(provider.heweather_now.data.now.cond_code)||getDarkskyWeatherIcon(provider.darksky.data.hourly.icon)}`, - //天气描述(晴/雨/雪等) - weather: `${provider.heweather_now.data.now.cond_txt||getDarkskyWeatherDesc(provider.darksky.data.hourly.icon)}`, - //当前温度 - currentTemperature: `${provider.heweather_now.data.now.tmp}`, - //温度最低值 - temperatureMin: `${Math.round(provider.heweather_daily.data.tmp_min||provider.darksky.data.daily.data.get(0).temperatureMin)}`, - //温度最高值 - temperatureMax: `${Math.round(provider.heweather_daily.data.tmp_max||provider.darksky.data.daily.data.get(0).temperatureMax)}`, - //体感温度最低值 - apparentTemperatureMin: `${Math.round(provider.darksky.data.daily.data.get(0).apparentTemperatureLow)}`, - //体感温度最高值 - apparentTemperatureMax: `${Math.round(provider.darksky.data.daily.data.get(0).apparentTemperatureHigh)}`, - //降雨概率 - precipProbability: `${provider.heweather_daily.data.pop||(Number(provider.darksky.data.daily.data.get(0).precipProbability) * 100).toFixed(0)}`, - //空气质量图标 - aqiIcon: `${provider.aqicn.data.aqiIcon||provider.heweather_air.data.aqiIcon}`, - //空气质量 - aqi: `${provider.aqicn.data.aqi||provider.heweather_air.data.aqi}`, - //空气质量描述 - aqiDesc: `${provider.aqicn.data.aqiDesc||provider.heweather_air.data.aqiDesc}`, - //空气质量警告(提示) - aqiWarning: `${provider.aqicn.data.aqiWarning||provider.heweather_air.data.aqiWarning}`, - //全天风速 - windSpeed: `${provider.heweather_daily.data.wind_spd}`, - //当前风速 - currentWindSpeed: `${provider.heweather_now.data.now.wind_spd}`, - //全天风向 - windDir: `${provider.heweather_daily.data.wind_dir}`, - //当前风向 - currentWindDir: `${provider.heweather_now.data.now.wind_dir}`, - //全天风力 - windPower: `${provider.heweather_daily.data.wind_sc}`, - //当前风力 - currentWindPower: `${provider.heweather_now.data.now.wind_sc}`, - //全天相对湿度 - humidity: `${provider.heweather_daily.data.hum}`, - //当前相对湿度 - currentHumidity: `${provider.heweather_now.data.now.hum}`, - //全天大气压 - atmosphere: `${provider.heweather_daily.data.pres}`, - //当前大气压 - currentAtmosphere: `${provider.heweather_now.data.now.pres}`, - //全天能见度 - visibility: `${provider.heweather_daily.data.vis}`, - //当前能见度 - currentVisibility: `${provider.heweather_now.data.now.vis}`, - //紫外线等级 - uv: `${provider.heweather_daily.data.uv_index||provider.darksky.data.daily.data.get(0).uvIndex}`, - //紫外线描述 - uvDesc: `${getUVDesc(provider.heweather_daily.data.uv_index||provider.darksky.data.daily.data.get(0).uvIndex)}`, - //日出时间 - sunrise: `${provider.heweather_daily.data.sr}`, - //日落时间 - sunset: `${provider.heweather_daily.data.ss}`, - //月出时间 - moonrise: `${provider.heweather_daily.data.mr}`, - //月落时间 - moonset: `${provider.heweather_daily.data.ms}`, - } - var notifyInfo = { - title: execTemplate(config.show.template.title, map), - subtitle: execTemplate(config.show.template.subtitle, map), - detail: execTemplate(config.show.template.detail, map), - }; - $notify(notifyInfo.title, notifyInfo.subtitle, notifyInfo.detail); - $done({}); -} -// #endregion - -// #region 数据处理方法 -function getHeweatherIcon(code) { - var codeMap = { - _100: '☀️', - _101: '☁️', - _102: '☁️', - _103: '⛅️', - _104: '☁️', - _200: '💨', - _201: '🌬', - _202: '🌬', - _203: '🌬', - _204: '🌬', - _205: '🌬', - _206: '💨', - _207: '💨', - _208: '💨', - _209: '🌪', - _210: '🌪', - _211: '🌪', - _212: '🌪', - _213: '🌪', - _300: '🌨', - _301: '🌨', - _302: '⛈', - _303: '⛈', - _304: '⛈', - _305: '💧', - _306: '💦', - _307: '🌧', - _308: '🌧', - _309: '☔️', - _310: '🌧', - _311: '🌧', - _312: '🌧', - _313: '🌧❄️', - _314: '💧', - _315: '💦', - _316: '🌧', - _317: '🌧', - _318: '🌧', - _399: '🌧', - _400: '🌨', - _401: '🌨', - _402: '☃️', - _403: '❄️', - _404: '🌨', - _405: '🌨', - _406: '🌨', - _407: '🌨', - _408: '🌨', - _409: '🌨', - _410: '❄️', - _499: '⛄️', - _500: '🌫', - _501: '🌫', - _502: '🌫', - _503: '🌫', - _504: '🌫', - _505: '🌫', - _506: '🌫', - _507: '🌫', - _508: '🌫', - _509: '🌫', - _510: '🌫', - _511: '🌫', - _512: '🌫', - _513: '🌫', - _514: '🌫', - _515: '🌫', - _900: '🔥', - _901: '⛄️', - _999: '❓', - } - return codeMap[`_${code}`] ? codeMap[`_${code}`] : ""; -} - -function getDarkskyWeatherIcon(icon_text) { - let icon = "❓" - if (icon_text == "clear-day") icon = "☀️"; - if (icon_text == "partly-cloudy-day") icon = "🌤"; - if (icon_text == "cloudy") icon = "☁️"; - if (icon_text == "rain") icon = "🌧"; - if (icon_text == "snow") icon = "☃️"; - if (icon_text == "sleet") icon = "🌨"; - if (icon_text == "wind") "🌬"; - if (icon_text == "fog") icon = "🌫"; - if (icon_text == "partly-cloudy-night") icon = "🌑"; - if (icon_text == "clear-night") icon = "🌑"; - return icon; -} - -function getDarkskyWeatherDesc(icon_text) { - let icon = "未知" - if (icon_text == "clear-day") icon = `晴`; - if (icon_text == "partly-cloudy-day") icon = `晴转多云`; - if (icon_text == "cloudy") icon = `多云`; - if (icon_text == "rain") icon = `雨`; - if (icon_text == "snow") icon = `雪`; - if (icon_text == "sleet") icon = `雨夹雪`; - if (icon_text == "wind") icon = `大风`; - if (icon_text == "fog") icon = `大雾`; - if (icon_text == "partly-cloudy-night") icon = `多云`; - if (icon_text == "clear-night") icon = `晴`; - return icon; -} - -function getCityInfo(name) { - var loc; - try { - var locArr = name.split(/[(),,()]/) - if (locArr.length >= 4) { - loc = locArr[2] + " "; - } else if (locArr.length >= 2) { - loc = locArr[1] + " "; - } else { - loc = ""; //此时会很长,还不如不显示了 - } - } catch (e) { - loc = ''; - record(`获取城市名称失败-${JSON.stringify(e)}`); - } - return loc; -} - -function getAqiInfo(aqi) { - var aqiDesc = ""; - var aqiIcon = ""; - var aqiWarning = ""; - if (aqi > 300) { - aqiIcon = `🟤`; - aqiDesc = `严重污染`; - aqiWarning = "儿童、老人、呼吸系统等疾病患者及一般人群停止户外活动"; - } else if (aqi > 200) { - aqiIcon = `🟣`; - aqiDesc = `重度污染`; - aqiWarning = "儿童、老人、呼吸系统等疾病患者及一般人群停止或减少户外运动"; - } else if (aqi > 150) { - aqiIcon = `🔴`; - aqiDesc = `中度污染`; - aqiWarning = "儿童、老人、呼吸系统等疾病患者及一般人群减少户外活动"; - } else if (aqi > 100) { - aqiIcon = `🟠`; - aqiDesc = `轻度污染`; - aqiWarning = "老人、儿童、呼吸系统等疾病患者减少长时间、高强度的户外活动"; - } else if (aqi > 50) { - aqiIcon = `🟡`; - aqiDesc = `良好`; - aqiWarning = "极少数敏感人群应减少户外活动"; - } else { - aqiIcon = `🟢`; - aqiDesc = `优`; - } - return { - aqi, - aqiIcon, - aqiDesc, - aqiWarning - }; -} - -function getUVDesc(daily_uvIndex) { - var uvDesc = ""; - if (daily_uvIndex >= 10) { - uvDesc = "五级-特别强"; - } else if (daily_uvIndex >= 7) { - uvDesc = "四级-很强"; - } else if (daily_uvIndex >= 5) { - uvDesc = "三级-较强"; - } else if (daily_uvIndex >= 3) { - uvDesc = "二级-较弱"; - } else { - uvDesc = "一级-最弱"; - } - return uvDesc; -} -// #endregion - -// #region 模板相关 -/** - * 用于标识该接口已执行,如果有使用超时设置则此操作是有意义的 - * @param {String} type 具体的接口执行类型 - */ -function start(type) { - if (config.timeout > 0) { - provider[type].timeoutNumber = setTimeout(() => { - check(type, false); - }, config.timeout); - } -} -/** - * 判断哪些接口需要进行处理,减少网络请求 - */ -function support() { - let regex = /\$\[([a-z,A-Z,0-9]*)\]/g; - const template = `${config.show.template.title}${config.show.template.subtitle}${config.show.template.detail}`.match(regex); - provider.heweather_now.progress = template.filter((item, filter) => { - return provider.heweather_now.support.indexOf(item) != -1; - }).length > 0 ? 0 : 2; - provider.heweather_daily.progress = template.filter((item, filter) => { - return provider.heweather_daily.support.indexOf(item) != -1; - }).length > 0 ? 0 : 2; - // provider.heweather_air.progress = template.filter((item, filter) => { - // return provider.heweather_air.support.indexOf(item) != -1; - // }).length > 0 ? 0 : 2; - provider.heweather_lifestyle.progress = template.filter((item, filter) => { - let regexLifestyle = /\$\[(lifeStyle\()+([\s\S]+?)(\))+\]/g; - return regexLifestyle.test(config.show.lifestyle) ? 0 : 2; - }).length > 0 ? 0 : 2; - provider.aqicn.progress = template.filter((item, filter) => { - return provider.aqicn.support.indexOf(item) != -1; - }).length > 0 ? 0 : 2; - provider.darksky.progress = template.filter((item, filter) => { - return provider.darksky.support.indexOf(item) != -1; - }).length > 0 ? 0 : 2; - if (provider.darksky.progress == 2) { - //如果 - let regexDaily = /\$\[(daily\()+([\s\S]+?)(\))+\]/g; - let regexHourly = /\$\[(hourly\()+([\s\S]+?)(\))+\]/g; - provider.darksky.progress = (regexDaily.test(config.show.template.detail) || regexHourly.test(config.show.template.detail)) ? 0 : 2; - } - record(`h_n:${provider.heweather_now.progress},h_d:${provider.heweather_daily.progress},h_a:${provider.heweather_air.progress},h_l:${provider.heweather_lifestyle.progress},aq:${provider.aqicn.progress},da:${provider.darksky.progress}`) -} -/** - * 用于普通模板的映射 - * @param {String} template 模板内容 - * @param {Object} map 映射内容 - */ -function execTemplate(template, map) { - if (!template) return ""; - let regex = /\$\[([a-z,A-Z,0-9]*)\]/g; - if (regex.test(template)) { - for (item of template.match(regex)) { - item.match(regex); - if (RegExp.$1 && map[RegExp.$1]) { - template = template.replace(item, map[RegExp.$1]); - } else { - template = template.replace(item, ""); - } - } - } - return template; -} - -function execArrayTemplate() { - try { - execTemplateLifestyle(); - execTemplateDaily(); - execTemplateHourly(); - } catch (e) { - console.log(`${JSON.stringify(e)}`) - } - -} - -function execTemplateLifestyle() { - let regexLifestyle = /\$\[(lifeStyle\()+([\s\S]+?)(\))+\]/g; - if (provider.heweather_lifestyle.data <= 0) { - config.show.template.detail.replace(regexLifestyle, '') - } - let result = []; - if (regexLifestyle.test(config.show.template.detail)) { - let lsMap = { //此处用于显示各项生活指数,可自行调整顺序,顺序越在前面则显示也会靠前,如果您不想查看某一指数,置为false即可,想看置为true即可 - drsg: { - icon: '👔', - type: '穿衣指数' - }, - flu: { - icon: '🤧', - type: '感冒指数' - }, - comf: { - icon: '😊', - type: '舒适度指数' - }, - cw: { - icon: '🚗', - type: '洗车指数' - }, - sport: { - icon: '🏃🏻', - type: '运动指数' - }, - trav: { - icon: '🌴', - type: '旅游指数' - }, - uv: { - icon: '☂️', - type: '紫外线指数' - }, - air: { - icon: '🌫', - type: '空气污染扩散条件指数' - }, - ac: { - icon: '❄️', - type: '空调开启指数' - }, - ag: { - icon: '😷', - type: '过敏指数' - }, - gl: { - icon: '🕶', - type: '太阳镜指数' - }, - mu: { - icon: '💄', - type: '化妆指数' - }, - airc: { - icon: '🧺', - type: '晾晒指数' - }, - ptfc: { - icon: '🚥', - type: '交通指数' - }, - fsh: { - icon: '🎣', - type: '钓鱼指数' - }, - spi: { - icon: '🔆', - type: '防晒指数' - }, - } - config.show.template.detail.match(regexLifestyle); - var rangeTemplate = RegExp.$2; //此处拿到的是要替换的列表显示部分了 - let regex = /\$\[([a-z,A-Z,0-9]*)\]/g; - var template = rangeTemplate.match(regex); - for (life of provider.heweather_lifestyle.data) { - if (!config.show.lifestyle[life.type]) continue; - var singleInfo = rangeTemplate; - for (item of template) { - item.match(regex); - if (RegExp.$1 == "icon") { - singleInfo = singleInfo.replace(item, lsMap[life.type].icon) - } else if (RegExp.$1 == "type") { - singleInfo = singleInfo.replace(item, lsMap[life.type].type) - } else { - singleInfo = singleInfo.replace(item, life[RegExp.$1]) - } - } - result.push(singleInfo); - } - config.show.template.detail = config.show.template.detail.replace(regexLifestyle, result.join(lineBreak)); - } -} - -function execTemplateDaily() { - let regexDaily = /\$\[(daily\()+([\s\S]+?)(\))+\]/g; - if (provider.darksky.data.daily.data.length <= 0) { - config.show.template.detail.replace(regexDaily, '') - } - let result = []; - if (regexDaily.test(config.show.template.detail)) { - config.show.template.detail.match(regexDaily); - var rangeTemplate = RegExp.$2; //此处拿到的是要替换的列表显示部分了 - let regex = /\$\[([a-z,A-Z,0-9]*)\]/g; - var template = rangeTemplate.match(regex); - for (daily of provider.darksky.data.daily.data) { - var singleInfo = rangeTemplate; - for (item of template) { - item.match(regex); - if (RegExp.$1 == "month") { - singleInfo = singleInfo.replace(item, (`${daily["time"]}`).toDateTime().Format("MM")); - } else if (RegExp.$1 == "day") { - singleInfo = singleInfo.replace(item, (`${daily["time"]}`).toDateTime().Format("dd")); - } else if (RegExp.$1 == "weatherIcon") { - singleInfo = singleInfo.replace(item, getDarkskyWeatherIcon(daily.icon)); - } else if (RegExp.$1 == "weather") { - singleInfo = singleInfo.replace(item, getDarkskyWeatherDesc(daily.icon)); - } else if (RegExp.$1 == "uvDesc") { - singleInfo = singleInfo.replace(item, getUVDesc(daily.uvIndex)); - } else if (RegExp.$1 == "cloudCover") { - singleInfo = singleInfo.replace(item, daily.cloudCover * 100); - } else if (RegExp.$1 == "temperatureHigh") { - singleInfo = singleInfo.replace(item, Math.round(daily.temperatureHigh)); - } else if (RegExp.$1 == "temperatureLow") { - singleInfo = singleInfo.replace(item, Math.round(daily.temperatureLow)); - } else if (RegExp.$1 == "apparentTemperatureMax") { - singleInfo = singleInfo.replace(item, Math.round(daily.apparentTemperatureMax)); - } else if (RegExp.$1 == "apparentTemperatureMin") { - singleInfo = singleInfo.replace(item, Math.round(daily.apparentTemperatureMin)); - } else if (RegExp.$1 && daily[RegExp.$1] != undefined) { - singleInfo = singleInfo.replace(item, daily[RegExp.$1]); - } - } - result.push(singleInfo); - } - config.show.template.detail = config.show.template.detail.replace(regexDaily, result.join(lineBreak)); - } -} - -function execTemplateHourly() { - let regexHourly = /\$\[(hourly\()+([\s\S]+?)(\))+\]/g; - if (provider.darksky.data.hourly.data.length <= 0) { - config.show.template.detail.replace(regexHourly, '') - } - let result = []; - if (regexHourly.test(config.show.template.detail)) { - config.show.template.detail.match(regexHourly); - var rangeTemplate = RegExp.$2; //此处拿到的是要替换的列表显示部分了 - let regex = /\$\[([a-z,A-Z,0-9]*)\]/g; - var template = rangeTemplate.match(regex); - for (hourly of provider.darksky.data.hourly.data) { - var singleInfo = rangeTemplate; - for (item of template) { - item.match(regex); - if (RegExp.$1 == "month") { - singleInfo = singleInfo.replace(item, (`${hourly["time"]}`).toDateTime().Format("MM")); - } else if (RegExp.$1 == "day") { - singleInfo = singleInfo.replace(item, (`${hourly["time"]}`).toDateTime().Format("dd")); - } else if (RegExp.$1 == "hour") { - singleInfo = singleInfo.replace(item, (`${hourly["time"]}`).toDateTime().Format("hh")); - } else if (RegExp.$1 == "weatherIcon") { - singleInfo = singleInfo.replace(item, getDarkskyWeatherIcon(hourly.icon)); - } else if (RegExp.$1 == "weather") { - singleInfo = singleInfo.replace(item, getDarkskyWeatherDesc(hourly.icon)); - } else if (RegExp.$1 == "uvDesc") { - singleInfo = singleInfo.replace(item, getUVDesc(hourly.uvIndex)); - } else if (RegExp.$1 == "cloudCover") { - singleInfo = singleInfo.replace(item, hourly.cloudCover * 100); - } else if (RegExp.$1 == "temperature") { - singleInfo = singleInfo.replace(item, Math.round(hourly.temperature)); - } else if (RegExp.$1 == "apparentTemperature") { - singleInfo = singleInfo.replace(item, Math.round(hourly.apparentTemperature)); - } else if (RegExp.$1 && hourly[RegExp.$1] != undefined) { - singleInfo = singleInfo.replace(item, hourly[RegExp.$1]); - } - } - result.push(singleInfo); - } - config.show.template.detail = config.show.template.detail.replace(regexHourly, result.join(lineBreak)); - } -} - -function record(log) { - if (config.log == 1) { - console.log(log); - } else if (config.log == 2) { - console.log(log.substring(0, 60)); - } -} -// #endregion - -// #region 扩展方法 -Array.prototype.get = function (index, defaultValue = {}) { - if (index >= 0 && this.length > 0 && this.length >= index + 1) { - return this[index]; - } else { - return defaultValue; - } -} -String.prototype.toDateTime = function () { - var time = parseInt(this + '000'); - return new Date(time); -} -Date.prototype.Format = function (fmt) { - var o = { - "M+": this.getMonth() + 1, //月份 - "d+": this.getDate(), //日 - "h+": this.getHours(), //小时 - "m+": this.getMinutes(), //分 - "s+": this.getSeconds(), //秒 - "q+": Math.floor((this.getMonth() + 3) / 3), //季度 - "S": this.getMilliseconds() //毫秒 - }; - if (/(y+)/.test(fmt)) - fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length)); - for (var k in o) - if (new RegExp("(" + k + ")").test(fmt)) - fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length))); - return fmt; -} -// #endregion -weather(); \ No newline at end of file diff --git a/Task/weibo.js b/Task/weibo.js index c7853188de..cefad3f11f 100644 --- a/Task/weibo.js +++ b/Task/weibo.js @@ -1,180 +1,197 @@ /* -更新时间: 2020-10-13 21:25 +更新时间: 2021-02-21 22:30 -本脚本仅适用于微博每日签到,支持Actions多账号运行 -获取Cookie方法: -1.将下方[rewrite_local]和[MITM]地址复制的相应的区域下 -2.打开微博App,刷微博视频,获取Cookie,获取后请注释或禁用Cookie -3.打开微博钱包点击签到,获取Cookie, -4.钱包签到时获取Cookie,已经签到无法获取 -5.非专业人士制作,欢迎各位大佬提出宝贵意见和指导 +本脚本仅适用于微博每日签到,支持多账号运行 -by Macsuny -~~~~~~~~~~~~~~~~ -Surge 4.0 : -[Script] -weibo.js = type=cron,cronexp=35 5 0 * * *,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/weibo.js,script-update-interval=0 -# 获取微博 Cookie. -weibo.js = type=http-request,pattern=https:\/\/api\.weibo\.cn\/\d\/page\/\w+\?gsid,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/weibo.js -# 微博钱包签到Cookie -weibo.js = type=http-request,pattern=https:\/\/pay\.sc\.weibo\.com\/aj\/mobile\/home\/welfare\/signin\/do\?,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/weibo.js - -~~~~~~~~~~~~~~~~ -Loon 2.1.0+ -[Script] -# 本地脚本 -cron "04 00 * * *" script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/weibo.js, enabled=true, tag=新浪微博 - -http-request https:\/\/api\.weibo\.cn\/\d\/page\/\w+\?gsid script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/weibo.js - -http-request https:\/\/pay\.sc\.weibo\.com\/aj\/mobile\/home\/welfare\/signin\/do\? script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/weibo.js - ------------------ - -QX 1.0.6+ : -[task_local] -0 9 * * * https://raw.githubusercontent.com/Sunert/Scripts/master/Task/weibo.js - -[rewrite_local] -https:\/\/api\.weibo\.cn\/\d\/page\/\w+\?gsid url script-request-header https://raw.githubusercontent.com/Sunert/Scripts/master/Task/weibo.js - -# 钱包签到Cookie -https:\/\/pay\.sc\.weibo\.com\/aj\/mobile\/home\/welfare\/signin\/do\? url script-request-header https://raw.githubusercontent.com/Sunert/Scripts/master/Task/weibo.js - -~~~~~~~~~~~~~~~~ -[MITM] -hostname = api.weibo.cn, pay.sc.weibo.com -~~~~~~~~~~~~~~~~ +获取ck: https:\/\/api\.weibo\.cn\/\d\/users\/show url script-request-header weibo.js */ const $ = new Env('新浪微博') const notify = $.isNode() ? require('./sendNotify') : ''; -let tokenArr = [],payArr = []; +let tokenArr = []; +let wbtoken = $.getdata('sy_token_wb'); +let cookies = $.getdata('wb_cookie'); +let signcash = "", cookieArr=[]; if (isGetCookie = typeof $request !==`undefined`) { GetCookie(); $.done() -} +} else{ +!(async () => { +if(!$.isNode()&&wbtoken.indexOf("#")==-1){ + tokenArr.push(wbtoken); + cookieArr.push(cookies) +} else { if ($.isNode()) { if (process.env.WB_TOKEN && process.env.WB_TOKEN.indexOf('#') > -1) { wbtoken = process.env.WB_TOKEN.split('#'); - console.log(`您选择的是用"#"隔开\n`) + console.log(`WB_TOKEN您选择的是用"#"隔开\n`) } else if (process.env.WB_TOKEN && process.env.WB_TOKEN.indexOf('\n') > -1) { wbtoken = process.env.WB_TOKEN.split('\n'); - console.log(`您选择的是用换行隔开\n`) + console.log(`WB_TOKEN您选择的是用换行隔开\n`) } else { - wbtoken = process.env.WB_TOKEN.split() + wbtoken = [process.env.WB_TOKEN] }; - if (process.env.WB_PAY && process.env.WB_PAY.indexOf('#') > -1) { - wbPay = process.env.WB_PAY.split('#'); + if (process.env.WB_COOKIE && process.env.WB_COOKIE.indexOf('#') > -1) { + cookies = process.env.WB_COOKIE.split('#'); + console.log(`WB_COOKIE您选择的是用"#"隔开\n`) } - else if (process.env.WB_PAY && process.env.WB_PAY.split('\n').length > 0) { - wbPay = process.env.WB_PAY.split('\n'); - } else { - wbPay = process.env.WB_PAY.split() + else if (process.env.WB_COOKIE && process.env.WB_COOKIE.indexOf('\n') > -1) { + cookies = process.env.WB_COOKIE.split('\n'); + console.log(`WB_COOKIE您选择的是用换行隔开\n`) + } else { + cookies = [process.env.WB_COOKIE] }; +} else if (!$.isNode()&&wbtoken.indexOf("#")>-1) { + wbtoken = wbtoken.split("#"); + cookies = cookies.split("#") +} Object.keys(wbtoken).forEach((item) => { if (wbtoken[item]) { tokenArr.push(wbtoken[item]) } }); - Object.keys(wbPay).forEach((item) => { - if (wbPay[item]) { - payArr.push(wbPay[item]) + Object.keys(cookies).forEach((item) => { + if (cookies[item]) { + cookieArr.push(cookies[item]) } }); - console.log(`============ 脚本执行-国际标准时间(UTC):${new Date().toLocaleString()} =============\n`) - console.log(`============ 脚本执行-北京时间(UTC+8):${new Date(new Date().getTime() + 8 * 60 * 60 * 1000).toLocaleString()} =============\n`) - } else { - tokenArr.push($.getdata('sy_token_wb')) - payArr.push($.getdata('sy_payheader_wb')) } - -!(async () => { if (!tokenArr[0]) { $.msg($.name, '【提示】请先获取新浪微博一cookie') return; } - console.log(`------------- 共${tokenArr.length}个账号\n`) + timeZone = new Date().getTimezoneOffset() / 60; + timestamp = Date.now()+ (8+timeZone) * 60 * 60 * 1000; + bjTime = new Date(timestamp).toLocaleString('zh',{hour12:false,timeZoneName: 'long'}); + console.log(`\n === 脚本执行 ${bjTime} ===\n`); + console.log(`------------- 共${tokenArr.length}个账号\n`) for (let i = 0; i < tokenArr.length; i++) { if (tokenArr[i]) { token = tokenArr[i]; - payheaderVal = payArr[i]; + cookie = cookieArr[i] $.index = i + 1; console.log(`\n开始【微博签到${$.index}】`) - await getsign(); - await doCard(); - if (payheaderVal !== undefined){ - await paysign() - } else { - paybag = `【钱包签到】❌ 未获取Cooiekie` - }; - $.msg($.name, nickname, wbsign+paybag+docard) - if ($.isNode()) { - await notify.sendNotify($.name, nickname+'\n'+ wbsign+paybag+docard) + if(token.indexOf("from")==-1){ + token += "from=10B2193010&" } + await getsign(); + await doCard(); + await paysign() + await showmsg() } } })() .catch((e) => $.logErr(e)) .finally(() => $.done()) - +} function GetCookie() { -if ($request && $request.method != 'OPTIONS' && $request.url.match(/\/\d\/[a-z]+\/\w+\?gsid/)) { - const signurlVal = $request.url - const token = signurlVal.split(`?`)[1] - //const signheaderVal = JSON.stringify($request.headers) - $.log(`token:${token}`) - if (token) $.setdata(token, 'sy_token_wb') - $.msg($.name, `获取微博签到Cookie: 成功`, ``) -} else if ($request && $request.method != 'OPTIONS' && $request.url.match(/\/home\/welfare\/signin\/do\?_=[1-9]+/)) { - const payheaderVal = JSON.stringify($request.headers) - if (payheaderVal) $.setdata(payheaderVal, 'sy_payheader_wb') - $.msg($.name, `获取微博钱包Cookie: 成功`, ``)} + if ($request && $request.method != 'OPTIONS' && $request.url.indexOf("gsid=") > -1) { + const signurlVal = $request.url; + let token = signurlVal.replace(/(.+)(from=\w+)(.+)(&uid=\d+)(.+)(&gsid=[_a-zA-Z0-9-]+)(&.+)(&s=\w+)(.+)/,'$2$4$6$8'), + uid = token.match(/uid=\d+/)[0]; + if (wbtoken) { + if (wbtoken.indexOf(uid) > -1) { + $.log("此账号Cookie已存在,本次跳过") + } else if (wbtoken.indexOf(uid) == -1) { + tokens = wbtoken + "#" + token; + $.setdata(tokens, 'sy_token_wb'); + $.log(`tokens: ${tokens}`) + $.msg($.name, `获取微博签到Cookie: 成功`, ``) + } + } else { + $.setdata(token, 'sy_token_wb'); + $.log(`tokens: ${token}`) + $.msg($.name, `获取微博签到Cookie: 成功`, ``) + } + } +else if ($request && $request.method != 'OPTIONS' && $request.headers.Cookie.indexOf("SUB=") > -1) { + const cookieval = $request.headers.Cookie.match(/SUB=[\w\-]+/)[0]; + if (cookies) { + if (cookies.indexOf(cookieval) > -1) { + $.log("此账号Cookie已存在,本次跳过") + } else if (cookies.indexOf(cookieval) == -1) { + cookie = cookies + "#" + cookieval; + $.setdata(cookie, 'wb_cookie'); + Cookies = cookie.split('#'); + $.log(`cookie: ${cookie}`); + $.msg($.name, '获取微博用户'+Cookies.length+'Cookie: 成功', ``) + } + } else { + $.setdata(cookieval, 'wb_cookie'); + $.log(`cookies: ${cookieval}`); + $.msg($.name, `获取微博用户Cookie: 成功`, ``) + } + } } - //微博签到 function getsign() { return new Promise((resolve, reject) =>{ let signurl = { - url: `https://api.weibo.cn/2/checkin/add?${token}`, - headers: {"User-Agent": `Weibo/46902 (iPhone; iOS 14; Scale/3.00)`}} - $.post(signurl, async(error, response, data) => { + url: `https://api.weibo.cn/2/checkin/add?c=iphone&${token}`, + headers: {"User-Agent": `Weibo/52021 (iPhone; iOS 14.5; Scale/3.00)`}} + $.get(signurl, async(error, resp, data) => { let result = JSON.parse(data) if (result.status == 10000){ wbsign = `【微博签到】✅ 连续签到${result.data.continuous}天,收益: ${result.data.desc}💰\n` } else if (result.errno == 30000){ - wbsign = `【每日签到】 🔁 ` + wbsign = `【每日签到】 🔁 已签到\n` + if(cookie){ + await getcash() + } } else if (result.status == 90005){ wbsign = `【每日签到】‼️`+ result.msg + '\n' - } - else { - wbsign = `【每日签到】 ❌ 签到失败`+result.errmsg - $.msg($.name, wbsign, ``) + } else { + wbsign = `【每日签到】 ❌ 签到失败 `+result.errmsg; + $.msg($.name, wbsign, `请检查微博Token`) if ($.isNode()) { await notify.sendNotify($.name, wbsign) } - return } resolve() }) }) } +function getcash() { + return new Promise((resolve, reject) =>{ + let url = { + url: `https://m.weibo.cn/c/checkin/getcashdetail`, + headers: {"User-Agent": `Mozilla/5.0 (iPhone; CPU iPhone OS 14_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 Weibo (iPhone10,2__weibo__11.2.1__iphone__os14.5)`, + Cookie: cookie + } + } + $.get(url, async(error, resp, data) => { + let cashres = JSON.parse(data) + if(cashres.apiCode==10000){ + signcash = " " + cashres.data.header[0].title+cashres.data.header[0].value+"元" + } + resolve() + }) + }) +} + + function doCard() { return new Promise((resolve, reject) =>{ let doCardurl = { - url: `https://api.weibo.cn/2/!/ug/king_act_home?${token}`, - headers: {"User-Agent": `Weibo/46902 (iPhone; iOS 14; Scale/3.00)`}} - $.get(doCardurl, (error, response, data) => { + url: `https://api.weibo.cn/2/!/ug/king_act_home?c=iphone&${token}`, + headers: {"User-Agent": `Weibo/52021 (iPhone; iOS 14.5; Scale/3.00)`}} + $.get(doCardurl, (error, resp, data) => { +//$.log(data) let result = JSON.parse(data) if (result.status ==10000){ nickname = "昵称: "+result.data.user.nickname + if(tokenArr.length==1){ + $.setdata(nickname,'wb_nick') + } else { + $.setdata(tokenArr.length+"合一(多账号)",'wb_nick') + } signday = result.data.signin.title.split('<')[0] docard = `【每日打卡】 ✅ `+ signday+'天 积分总计: '+result.data.user.energy } @@ -189,23 +206,59 @@ function doCard() { // 钱包签到 function paysign() { return new Promise((resolve, reject) =>{ - $.post({url: `https://pay.sc.weibo.com/aj/mobile/home/welfare/signin/do?_=${$.startTime+10}`,headers: JSON.parse(payheaderVal) - }, (error, response, data) => { - try{ + $.post(payApi('aj/mobile/home/welfare/signin/do?_='+$.startTime+10), async(error, resp, data) => { let result = JSON.parse(data) if (result.status == 1){ paybag = `【微博钱包】 ✅ +`+ result.score+' 分\n' } - else if (result.code == 100000){ - paybag = `【微博钱包】 🔁\n` + else if (result.status == '2'){ + paybag = `【微博钱包】 🔁 ` + await payinfo() } - } - catch(error){ - paybag = `【钱包签到】❌ Cookie失效`+'\n' - } - resolve() + else { + paybag = `【钱包签到】❌ Cookie失效`+'\n' + } + resolve() + }) }) } +function payApi(api) { + return { + url: 'https://pay.sc.weibo.com/'+api, + headers:{ + 'Accept-Encoding': 'gzip, deflate', + 'Connection': 'keep-alive', + 'Content-Type': 'application/x-www-form-urlencoded', + 'Host': 'pay.sc.weibo.com', + 'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 Weibo (iPhone10,1__weibo__11.2.1__iphone__os14.5)' + }, + body: token+'&lang=zh_CN&wm=3333_2001' + } +} + +function payinfo() { + return new Promise((resolve, reject) =>{ + $.post(payApi('api/client/sdk/app/balance'), (error, resp, data) => { + let paynum = JSON.parse(data) + if (paynum.code == 100000){ + paybag += '现金:'+ paynum.data.balance+' 元\n' + } + resolve() + }) + }) +} + +async function showmsg() { + if (paybag) { + $.msg($.name, nickname+(signcash?signcash:""), wbsign+paybag+docard); + if ($.isNode()) { + await notify.sendNotify($.name, nickname+(signcash?signcash:"")+'\n'+ wbsign+paybag+docard) + } + } +} + + + function Env(t,e){class s{constructor(t){this.env=t}send(t,e="GET"){t="string"==typeof t?{url:t}:t;let s=this.get;return"POST"===e&&(s=this.post),new Promise((e,i)=>{s.call(this,t,(t,s,r)=>{t?i(t):e(s)})})}get(t){return this.send.call(this.env,t)}post(t){return this.send.call(this.env,t,"POST")}}return new class{constructor(t,e){this.name=t,this.http=new s(this),this.data=null,this.dataFile="box.dat",this.logs=[],this.isMute=!1,this.isNeedRewrite=!1,this.logSeparator="\n",this.startTime=(new Date).getTime(),Object.assign(this,e),this.log("",`\ud83d\udd14${this.name}, \u5f00\u59cb!`)}isNode(){return"undefined"!=typeof module&&!!module.exports}isQuanX(){return"undefined"!=typeof $task}isSurge(){return"undefined"!=typeof $httpClient&&"undefined"==typeof $loon}isLoon(){return"undefined"!=typeof $loon}toObj(t,e=null){try{return JSON.parse(t)}catch{return e}}toStr(t,e=null){try{return JSON.stringify(t)}catch{return e}}getjson(t,e){let s=e;const i=this.getdata(t);if(i)try{s=JSON.parse(this.getdata(t))}catch{}return s}setjson(t,e){try{return this.setdata(JSON.stringify(t),e)}catch{return!1}}getScript(t){return new Promise(e=>{this.get({url:t},(t,s,i)=>e(i))})}runScript(t,e){return new Promise(s=>{let i=this.getdata("@chavy_boxjs_userCfgs.httpapi");i=i?i.replace(/\n/g,"").trim():i;let r=this.getdata("@chavy_boxjs_userCfgs.httpapi_timeout");r=r?1*r:20,r=e&&e.timeout?e.timeout:r;const[o,h]=i.split("@"),a={url:`http://${h}/v1/scripting/evaluate`,body:{script_text:t,mock_type:"cron",timeout:r},headers:{"X-Key":o,Accept:"*/*"}};this.post(a,(t,e,i)=>s(i))}).catch(t=>this.logErr(t))}loaddata(){if(!this.isNode())return{};{this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(this.dataFile),e=this.path.resolve(process.cwd(),this.dataFile),s=this.fs.existsSync(t),i=!s&&this.fs.existsSync(e);if(!s&&!i)return{};{const i=s?t:e;try{return JSON.parse(this.fs.readFileSync(i))}catch(t){return{}}}}}writedata(){if(this.isNode()){this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(this.dataFile),e=this.path.resolve(process.cwd(),this.dataFile),s=this.fs.existsSync(t),i=!s&&this.fs.existsSync(e),r=JSON.stringify(this.data);s?this.fs.writeFileSync(t,r):i?this.fs.writeFileSync(e,r):this.fs.writeFileSync(t,r)}}lodash_get(t,e,s){const i=e.replace(/\[(\d+)\]/g,".$1").split(".");let r=t;for(const t of i)if(r=Object(r)[t],void 0===r)return s;return r}lodash_set(t,e,s){return Object(t)!==t?t:(Array.isArray(e)||(e=e.toString().match(/[^.[\]]+/g)||[]),e.slice(0,-1).reduce((t,s,i)=>Object(t[s])===t[s]?t[s]:t[s]=Math.abs(e[i+1])>>0==+e[i+1]?[]:{},t)[e[e.length-1]]=s,t)}getdata(t){let e=this.getval(t);if(/^@/.test(t)){const[,s,i]=/^@(.*?)\.(.*?)$/.exec(t),r=s?this.getval(s):"";if(r)try{const t=JSON.parse(r);e=t?this.lodash_get(t,i,""):e}catch(t){e=""}}return e}setdata(t,e){let s=!1;if(/^@/.test(e)){const[,i,r]=/^@(.*?)\.(.*?)$/.exec(e),o=this.getval(i),h=i?"null"===o?null:o||"{}":"{}";try{const e=JSON.parse(h);this.lodash_set(e,r,t),s=this.setval(JSON.stringify(e),i)}catch(e){const o={};this.lodash_set(o,r,t),s=this.setval(JSON.stringify(o),i)}}else s=this.setval(t,e);return s}getval(t){return this.isSurge()||this.isLoon()?$persistentStore.read(t):this.isQuanX()?$prefs.valueForKey(t):this.isNode()?(this.data=this.loaddata(),this.data[t]):this.data&&this.data[t]||null}setval(t,e){return this.isSurge()||this.isLoon()?$persistentStore.write(t,e):this.isQuanX()?$prefs.setValueForKey(t,e):this.isNode()?(this.data=this.loaddata(),this.data[e]=t,this.writedata(),!0):this.data&&this.data[e]||null}initGotEnv(t){this.got=this.got?this.got:require("got"),this.cktough=this.cktough?this.cktough:require("tough-cookie"),this.ckjar=this.ckjar?this.ckjar:new this.cktough.CookieJar,t&&(t.headers=t.headers?t.headers:{},void 0===t.headers.Cookie&&void 0===t.cookieJar&&(t.cookieJar=this.ckjar))}get(t,e=(()=>{})){t.headers&&(delete t.headers["Content-Type"],delete t.headers["Content-Length"]),this.isSurge()||this.isLoon()?(this.isSurge()&&this.isNeedRewrite&&(t.headers=t.headers||{},Object.assign(t.headers,{"X-Surge-Skip-Scripting":!1})),$httpClient.get(t,(t,s,i)=>{!t&&s&&(s.body=i,s.statusCode=s.status),e(t,s,i)})):this.isQuanX()?(this.isNeedRewrite&&(t.opts=t.opts||{},Object.assign(t.opts,{hints:!1})),$task.fetch(t).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>e(t))):this.isNode()&&(this.initGotEnv(t),this.got(t).on("redirect",(t,e)=>{try{if(t.headers["set-cookie"]){const s=t.headers["set-cookie"].map(this.cktough.Cookie.parse).toString();this.ckjar.setCookieSync(s,null),e.cookieJar=this.ckjar}}catch(t){this.logErr(t)}}).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>{const{message:s,response:i}=t;e(s,i,i&&i.body)}))}post(t,e=(()=>{})){if(t.body&&t.headers&&!t.headers["Content-Type"]&&(t.headers["Content-Type"]="application/x-www-form-urlencoded"),t.headers&&delete t.headers["Content-Length"],this.isSurge()||this.isLoon())this.isSurge()&&this.isNeedRewrite&&(t.headers=t.headers||{},Object.assign(t.headers,{"X-Surge-Skip-Scripting":!1})),$httpClient.post(t,(t,s,i)=>{!t&&s&&(s.body=i,s.statusCode=s.status),e(t,s,i)});else if(this.isQuanX())t.method="POST",this.isNeedRewrite&&(t.opts=t.opts||{},Object.assign(t.opts,{hints:!1})),$task.fetch(t).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>e(t));else if(this.isNode()){this.initGotEnv(t);const{url:s,...i}=t;this.got.post(s,i).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>{const{message:s,response:i}=t;e(s,i,i&&i.body)})}}time(t){let e={"M+":(new Date).getMonth()+1,"d+":(new Date).getDate(),"H+":(new Date).getHours(),"m+":(new Date).getMinutes(),"s+":(new Date).getSeconds(),"q+":Math.floor(((new Date).getMonth()+3)/3),S:(new Date).getMilliseconds()};/(y+)/.test(t)&&(t=t.replace(RegExp.$1,((new Date).getFullYear()+"").substr(4-RegExp.$1.length)));for(let s in e)new RegExp("("+s+")").test(t)&&(t=t.replace(RegExp.$1,1==RegExp.$1.length?e[s]:("00"+e[s]).substr((""+e[s]).length)));return t}msg(e=t,s="",i="",r){const o=t=>{if(!t)return t;if("string"==typeof t)return this.isLoon()?t:this.isQuanX()?{"open-url":t}:this.isSurge()?{url:t}:void 0;if("object"==typeof t){if(this.isLoon()){let e=t.openUrl||t.url||t["open-url"],s=t.mediaUrl||t["media-url"];return{openUrl:e,mediaUrl:s}}if(this.isQuanX()){let e=t["open-url"]||t.url||t.openUrl,s=t["media-url"]||t.mediaUrl;return{"open-url":e,"media-url":s}}if(this.isSurge()){let e=t.url||t.openUrl||t["open-url"];return{url:e}}}};this.isMute||(this.isSurge()||this.isLoon()?$notification.post(e,s,i,o(r)):this.isQuanX()&&$notify(e,s,i,o(r)));let h=["","==============\ud83d\udce3\u7cfb\u7edf\u901a\u77e5\ud83d\udce3=============="];h.push(e),s&&h.push(s),i&&h.push(i),console.log(h.join("\n")),this.logs=this.logs.concat(h)}log(...t){t.length>0&&(this.logs=[...this.logs,...t]),console.log(t.join(this.logSeparator))}logErr(t,e){const s=!this.isSurge()&&!this.isQuanX()&&!this.isLoon();s?this.log("",`\u2757\ufe0f${this.name}, \u9519\u8bef!`,t.stack):this.log("",`\u2757\ufe0f${this.name}, \u9519\u8bef!`,t)}wait(t){return new Promise(e=>setTimeout(e,t))}done(t={}){const e=(new Date).getTime(),s=(e-this.startTime)/1e3;this.log("",`\ud83d\udd14${this.name}, \u7ed3\u675f! \ud83d\udd5b ${s} \u79d2`),this.log(),(this.isSurge()||this.isQuanX()||this.isLoon())&&$done(t)}}(t,e)} diff --git a/Task/youth.js b/Task/youth.js index dd81394782..204018e525 100644 --- a/Task/youth.js +++ b/Task/youth.js @@ -1,560 +1,686 @@ /* -更新时间: 2020-09-25 18:15 +更新时间: 2021-02-23 23:55 赞赏:中青邀请码`46308484`,农妇山泉 -> 有点咸,万分感谢 本脚本仅适用于中青看点极速版领取青豆 - -获取Cookie方法: -1.将下方[rewrite_local]和[MITM]地址复制的相应的区域 -下,运行时间自行配置 -2. 获取Cookie方法,可随时更新 - ① 进入app,进入任务中心或者签到一次,即可获取Cookie. - ② 阅读一篇文章,获取阅读请求body, - ③ 同时获取阅读时长, - ④ 在阅读文章最下面有个惊喜红包,点击获取惊喜红包请求 -3.增加转盘抽奖通知间隔,为了照顾新用户,前三次会有通知,以后默认每50次转盘抽奖通知一次,可自行修改❗️ 转盘完成后通知会一直开启 -4.非专业人士制作,欢迎各位大佬提出宝贵意见和指导 -5.增加每日打卡,打卡时间每日5:00-8:00❗️,请不要忘记设置运行时间,共4条Cookie,请全部获取,获取请注释 -6. 支持Github Actions多账号运行,填写'YOUTH_HEADER'值多账号时用'#'号隔开,其余值均用'&'分割 ‼️,当转盘次数为50或者100并且余额大于10元时推送通知 - -~~~~~~~~~~~~~~~~ -Surge 4.0 : -[Script] -中青看点 = type=cron,cronexp=35 5 0 * * *,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/youth.js,script-update-interval=0 - -中青看点 = type=http-request,pattern=https:\/\/\w+\.youth\.cn\/TaskCenter\/(sign|getSign),script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/youth.js - -中青看点 = type=http-request,pattern=https:\/\/ios\.baertt\.com\/v5\/article\/complete,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/youth.js, requires-body=true - -中青看点 = type=http-request,pattern=https:\/\/ios\.baertt\.com\/v5\/article\/red_packet,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/youth.js, requires-body=true - -中青看点 = type=http-request,pattern=https:\/\/ios\.baertt\.com\/v5\/user\/app_stay\.json,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/youth.js, requires-body=true - -~~~~~~~~~~~~~~~~ -Loon 2.1.0+ -[Script] -# 本地脚本 -cron "04 00 * * *" script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/youth.js, enabled=true, tag=中青看点 - -http-request https:\/\/\w+\.youth\.cn\/TaskCenter\/(sign|getSign) script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/youth.js -http-request https:\/\/ios\.baertt\.com\/v5\/article\/complete script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/youth.js, requires-body=true -http-request https:\/\/ios\.baertt\.com\/v5\/article\/red_packet script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/youth.js, requires-body=true -http-request https:\/\/ios\.baertt\.com\/v5\/user\/app_stay\.json script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/youth.js, requires-body=true ------------------ -QX 1.0. 7+ : -[task_local] -0 9 * * * youth.js - -[rewrite_local] -https:\/\/\w+\.youth\.cn\/TaskCenter\/(sign|getSign) url script-request-header youth.js - -https?:\/\/ios\.baertt\.com\/v5\/article\/complete url script-request-body youth.js - -https:\/\/ios\.baertt\.com\/v5\/article\/red_packet url script-request-body youth.js - -https:\/\/ios\.baertt\.com\/v5\/user\/app_stay\.json url script-request-body youth.js - - -~~~~~~~~~~~~~~~~ -[MITM] -hostname = *.youth.cn, ios.baertt.com -~~~~~~~~~~~~~~~~ +食用说明请查看本仓库目录Taskconf/youth/readme.md,其中打卡挑战赛可通过Boxjs开关,报名时间为23点,早起打卡时间为早5点,报名需1000青豆押金,打卡成功可返1000+青豆,打卡失败则押金不予返还,请注意时间运行, +转发文章获得青豆不实,请无视 */ -let s = 200 //各数据接口延迟 const $ = new Env("中青看点") -let notifyInterval = $.getdata("notifytimes")||50 //通知间隔,默认抽奖每50次通知一次,如需关闭全部通知请设为0 -const YOUTH_HOST = "https://kd.youth.cn/WebApi/"; + const notify = $.isNode() ? require('./sendNotify') : ''; -let logs = $.getdata('zqlogs')||false, signresult; -let cookiesArr = [], signheaderVal = '', - readArr = [], articlebodyVal ='', - timeArr = [], timebodyVal = '', - redpArr = [], redpbodyVal = ''; -let CookieYouth = [] ,ARTBODYs = [], - REDBODYs = [], READTIME = []; -if ($.isNode()) { - if (process.env.YOUTH_HEADER && process.env.YOUTH_HEADER.indexOf('#') > -1) { - CookieYouth = process.env.YOUTH_HEADER.split('#'); - } else { - CookieYouth = process.env.YOUTH_HEADER.split() - }; - - if (process.env.YOUTH_ARTBODY && process.env.YOUTH_ARTBODY.indexOf('&') > -1) { - ARTBODYs = process.env.YOUTH_ARTBODY.split('&'); - } else { - ARTBODYs = process.env.YOUTH_ARTBODY.split() - }; - - if (process.env.YOUTH_REDBODY && process.env.YOUTH_REDBODY.indexOf('&') > -1) { - REDBODYs = process.env.YOUTH_REDBODY.split('&'); +//const youthNode = $.isNode() ? require('./youth_env') : ''; + +// 可设置部分 +let notifyInterval = $.getdata("notifytimes")||50 //通知间隔,默认抽奖每50次通知一次,如需关闭全部通知请设为0 +let ONCard = $.getdata('zqcard')||"false" //早起打卡开关 +let s = $.getdata('delay_rotary_zq')||"10" //转盘延迟时间 +let withdrawcash = $.getdata('zqcash')||30 //提现金额 +let cardTime = $.getdata('zqtime')||"05";//打卡时间 + +// 需获取部分 +let withdrawUrl = $.getdata('cashurl_zq'); //提现地址,可选 +let withdrawBody = $.getdata('cashbody_zq'); //提现请求,可选 +let cookieYouth = $.getdata('youthheader_zq'); +let artBody = $.getdata('read_zq'); +let readTimes = $.getdata('readtime_zq'); + +//声明部分 +let rotaryscore=0,doublerotary=0; +let cookieArr = [], cookie = '', + readArr = [], articbody ='', + timeArr = [], timebody = '', + detail = ``, subTitle = ``; + +// 脚本部分 +if (isGetCookie = typeof $request !== 'undefined') { + GetCookie(); + $.done() +} else if (!$.isNode() && !cookieYouth) { + $.msg($.name, "您未获取中青Cookie","请进入任务中心获取") +} else { + !(async() =>{ + if (!$.isNode() && cookieYouth.indexOf("#") == -1) { + cookieArr.push(cookieYouth); + readArr.push(artBody); + timeArr.push(readTimes) } else { - REDBODYs = process.env.YOUTH_REDBODY.split() - }; - - if (process.env.YOUTH_TIME && process.env.YOUTH_TIME.indexOf('&') > -1) { - READTIME = process.env.YOUTH_TIME.split('&'); - }else { - READTIME = process.env.YOUTH_TIME.split() + if (!$.isNode() && cookieYouth.indexOf("#") > -1) { + cookieYouth = cookieYouth.split("#"), + artBody = artBody.split("&"), + readTimes = readTimes.split("&") + } else if($.isNode()){ + if (process.env.YOUTH_HEADER && process.env.YOUTH_HEADER.indexOf('#') > -1) { + cookieYouth = process.env.YOUTH_HEADER.split('#'); + } else if (process.env.YOUTH_HEADER && process.env.YOUTH_HEADER.indexOf('\n') > -1) { + cookieYouth = process.env.YOUTH_HEADER.split('\n'); + } else { + cookieYouth = [process.env.YOUTH_HEADER] + }; + if (process.env.YOUTH_ARTBODY && process.env.YOUTH_ARTBODY.indexOf('&') > -1) { + artBody = process.env.YOUTH_ARTBODY.split('&'); + } else if (process.env.YOUTH_ARTBODY && process.env.YOUTH_ARTBODY.indexOf('\n') > -1) { + artBody = process.env.YOUTH_ARTBODY.split('\n'); + } else { + artBody = [process.env.YOUTH_ARTBODY] + }; + if (process.env.YOUTH_TIME && process.env.YOUTH_TIME.indexOf('&') > -1) { + readTimes = process.env.YOUTH_TIME.split('&'); + } else if (process.env.YOUTH_TIME && process.env.YOUTH_TIME.indexOf('\n') > -1) { + readTimes = process.env.YOUTH_TIME.split('\n'); + } else { + readTimes = [process.env.YOUTH_TIME] + } + }; + Object.keys(cookieYouth).forEach((item) =>{ + if (cookieYouth[item]) { + cookieArr.push(cookieYouth[item]) + } + }); + Object.keys(artBody).forEach((item) =>{ + if (artBody[item]) { + readArr.push(artBody[item]) + } + }); + Object.keys(readTimes).forEach((item) =>{ + if (readTimes[item]) { + timeArr.push(readTime[item]) + } + }) }; + timeZone = new Date().getTimezoneOffset() / 60; + timestamp = Date.now() + (8 + timeZone) * 60 * 60 * 1000; + bjTime = new Date(timestamp).toLocaleString('zh', {hour12: false,timeZoneName: 'long'}); + $.log(`\n === 脚本执行${bjTime} === \n`); + $.log(` =========== 您共提供${cookieArr.length}个中青账号 ==========`); + if (!cookieArr[0]) { + $.msg($.name, '【提示】请先获取中青看点一cookie', "", {'open-url': "https://kandian.youth.cn/u/mhkjN"}); + return; + } + for (let i = 0; i < cookieArr.length; i++) { + if (cookieArr[i]) { + cookie = cookieArr[i]; + articbody = readArr[i]; + timebody = timeArr[i]; + $.index = i + 1; + }; + myuid = cookie.match(/uid=\d+/); + await userInfo(); + nick = nick ? nick: null; + $.log(`\n ********** ${nick} 现金: ${cash}元 ********\n`); + await bonusTask(); + await TaskCenter(); + await openbox(); + await getAdVideo(); + await gameVideo(); + await readArticle(); + $.log("开始转盘抽奖任务"); + for (k = 0; k < 5; k++) { + await $.wait(s*1000); + await rotary(); + if (rotaryres.status == 0) { + rotarynum = `转盘${rotaryres.msg}🎉`; + break + } + } + if (rotaryres.status == 1) { + detail += `【转盘抽奖】 + ${rotaryscore}个青豆剩余${rotarytimes}次\n`; + $.log(`转盘抽奖: 共计 + ${rotaryscore}个青豆剩余${rotarytimes}次`); + if (doubleTimes !== 0) { + detail += `【转盘双倍】 + ${doublerotary}青豆剩余${doubleTimes}次\n`; + $.log(`转盘双倍: +${doublerotary}青豆剩余${doubleTimes}次`) + } + } + await earningsInfo(); + await showmsg() + } + })() + .catch((e) =>$.logErr(e)) + .finally(() =>$.done()) } - -if ($.isNode()) { - Object.keys(CookieYouth).forEach((item) => { - if (CookieYouth[item]) { - cookiesArr.push(CookieYouth[item]) - } - }) - Object.keys(ARTBODYs).forEach((item) => { - if (ARTBODYs[item]) { - readArr.push(ARTBODYs[item]) - } - }) - Object.keys(REDBODYs).forEach((item) => { - if (REDBODYs[item]) { - redpArr.push(REDBODYs[item]) + +function kdHost(api,body) { + return { + url: 'https://kd.youth.cn/'+api+`&${myuid}`, + headers:{ + 'Accept': '*/*', + 'Accept-Encoding': 'gzip, deflate, br', + 'Referer': 'https://kd.youth.cn/h5/20190301taskcenter/ios/index.html?'+cookie, + 'Host': 'kd.youth.cn', + 'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148', + 'X-Requested-With': 'XMLHttpRequest' + }, + body: body, + //timeout: 1000, + } +} +function userInfo() { + return new Promise((resolve, reject) =>{ + $.post(kdHost('WebApi/NewTaskIos/getSign'), async(error, resp, data) =>{ + signinfo = JSON.parse(data); + if (signinfo.status == 1) { + cash = signinfo.data.user.money; + signday = signinfo.data.sign_day; + totalscore = signinfo.data.user.score; + subTitle = `【收益总计】${totalscore}青豆 现金约${cash}元`; + nick = '账号:'+signinfo.data.user.nickname; + if (cookieArr.length == 1) { + $.setdata(nick, "zq_nick") + } else { + $.setdata("账号" + cookieArr.length + "合一", "zq_nick") } - }) - Object.keys(READTIME).forEach((item) => { - if (READTIME[item]) { - timeArr.push(READTIME[item]) + if (parseInt(cash) >= withdrawcash && !withdrawBody == false) { + await withDraw() + }; + if (signinfo.data.is_sign == false) { + await getsign(); + } else if (signinfo.data.is_sign == true) { + detail = `【签到结果】🔁 (今天+${signinfo.data.sign_score}青豆)已连签${signday}天\n<本次收益> :\n` + }; + if (signday == 7) { + await SevCont(); } - }) - console.log(`============ 共${cookiesArr.length}个中青账号 =============\n`) - console.log(`============ 脚本执行-国际标准时间(UTC):${new Date().toLocaleString()} =============\n`) - console.log(`============ 脚本执行-北京时间(UTC+8):${new Date(new Date().getTime() + 8 * 60 * 60 * 1000).toLocaleString()} =============\n`) - } else { - cookiesArr.push($.getdata('youthheader_zq')); - redpArr.push($.getdata('red_zq')); - readArr.push($.getdata('read_zq')); - timeArr.push($.getdata('readtime_zq')); + } else { + $.log(signinfo.msg); + return + } + resolve() + }) + }) } -const firstcheck = $.getdata('signt'); -const runtimes = $.getdata('times'); -const opboxtime = $.getdata('opbox'); +function TaskCenter() { + return new Promise((resolve, reject) =>{ + $.post(kdHost('WebApi/NewTaskIos/getTaskList?'), async(error, resp, data) =>{ + try { + taskres = JSON.parse(data); + //$.log(JSON.stringify(taskres,null,2)); + if (taskres.status == 1) { + await friendsign(); + for (dailys of taskres.list.daily) { + await $.wait(500); + if (dailys.status == "1" && dailys.action != "") { + $.log(dailys.title + "已完成 ,去领取奖励青豆"); + await $.wait(600); + await getAction(dailys.reward_action) + } else if (dailys.status == "2" && dailys.action != "") { + $.log(dailys.title + "," + dailys.but + ",已领取青豆" + dailys.score) + detail += `【${dailys.title}】✅ ${dailys.score}青豆\n` + } + else if (dailys.title=="打卡赚钱"&&dailys.status == "0"&&ONCard == "true") { + await CardStatus() + } + else if (dailys.id == "7" && dailys.status == "0") { + await readTime(); + } + else if (dailys.title == "新春额外赚" && dailys.status == "0") { + await Census(); + } + else if (dailys.id == "10" && dailys.status == "0") { + $.log(dailys.title + "未完成,去做任务"); + for (x = 0; x < 5; x++) { + $.log("等待5s执行第" + (x + 1) + "次"); + await $.wait(5000); + await recordAdVideo(dailys.reward_action) + } + if (record.status == 0) { + await getAction(dailys.reward_action); + } + } + } + } + } catch(e) { + $.log("获取任务失败," + e) + } finally { + resolve() + } + }) + }) +} -if (isGetCookie = typeof $request !== 'undefined') { - GetCookie(); - $.done() -} - - !(async () => { - if (!cookiesArr[0]) { - $.msg($.name, '【提示】请先获取中青看点一cookie') - return; - } - for (let i = 0; i < cookiesArr.length; i++) { - if (cookiesArr[i]) { - signheaderVal = cookiesArr[i]; - articlebodyVal = readArr[i]; - timebodyVal = timeArr[i]; - redpbodyVal = redpArr[i]; - $.index = i + 1; - console.log(`-------------------------\n\n开始【中青看点${$.index}】`) - } - await sign(); - await signInfo(); - await Invitant(); -if($.time('HH')>12){ - await punchCard() -}; -if ($.isNode()&& $.time('HH')>20&&$.time('HH')<22){ - await endCard(); - } -else if ($.time('HH')>4&&$.time('HH')<8){ - await endCard(); - } - await openbox(); - await getAdVideo(); - await gameVideo(); - await readArticle(); - await Articlered(); - await readTime(); - await rotary(); - await rotaryCheck(); - await earningsInfo(); - await showmsg(); - if ($.isNode()) - if(rotaryres.data.remainTurn%50 == 0 && cash >= 10){ - await notify.sendNotify($.name + " " + nick, "您的余额约为"+cash+"元,已可以提现"+'\n'+`【收益总计】${signinfo.data.user.score}青豆 现金约${cash}元\n${detail}`) - } - } -})() - .catch((e) => $.logErr(e)) - .finally(() => $.done()) - - -function GetCookie() { - if ($request && $request.method != `OPTIONS`&& $request.url.match(/\/TaskCenter\/(sign|getSign)/)) { - const signheaderVal = JSON.stringify($request.headers) - if (signheaderVal) $.setdata(signheaderVal,'youthheader_zq') - $.log(`${$.name} 获取Cookie: 成功,signheaderVal: ${signheaderVal}`) - $.msg($.name, `获取Cookie: 成功🎉`, ``) - } -else if ($request && $request.method != `OPTIONS`&& $request.url.match(/\/article\/complete/)) { - const articlebodyVal = $request.body - if (articlebodyVal) $.setdata(articlebodyVal,'read_zq') - $.log(`${$.name} 获取阅读: 成功,articlebodyVal: ${articlebodyVal}`) - $.msg($.name, `获取阅读请求: 成功🎉`, ``) - } -else if ($request && $request.method != `OPTIONS`&& $request.url.match(/\/v5\/user\/app_stay/)) { - const timebodyVal = $request.body - if (timebodyVal) $.setdata(timebodyVal,'readtime_zq') - $.log(`${$.name} 获取阅读: 成功,timebodyVal: ${timebodyVal}`) - $.msg($.name, `获取阅读时长: 成功🎉`, ``) - } -else if ($request && $request.method != `OPTIONS`&& $request.url.match(/\/article\/red_packet/)) { - const redpbodyVal = $request.body - if (redpbodyVal) $.setdata(redpbodyVal, 'red_zq') - $.log(`${$.name} 获取惊喜红包: 成功,redpbodyVal: ${redpbodyVal}`) - $.msg($.name, `获取惊喜红包请求: 成功🎉`, ``) - } - } +function getAction(acttype) { + return new Promise((resolve, reject) =>{ + $.get(kdHost('WebApi/NewTaskIos/sendTwentyScore?action='+acttype), (error, resp, data) =>{ + let actres = JSON.parse(data); + if (actres.status == 1) { + $.log("获得青豆" + actres.score) + } else if (actres.status == 0) { + $.log(actres.msg) + } + resolve() + }) + }) +} -function sign() { - return new Promise((resolve, reject) => { - const signurl = { - url: 'https://kd.youth.cn/TaskCenter/sign', - headers: JSON.parse(signheaderVal), - } - $.post(signurl, (error, response, data) => { - signres = JSON.parse(data) - const date = $.time(`MMdd`) +function getsign() { + return new Promise((resolve, reject) =>{ + $.post(kdHost('WebApi/NewTaskIos/sign'), async(error, resp, data) =>{ + signres = JSON.parse(data); if (signres.status == 2) { - signresult = `签到失败,Cookie已失效‼️`; - $.msg($.name, signresult, ""); + sub = `签到失败,Cookie已失效‼️`; + $.msg($.name, sub, ""); return; } else if (signres.status == 1) { - signresult = `【签到结果】成功 🎉 明日+${signres.nextScore} ` - //detail = `【签到结果】成功 🎉 青豆: +${signres.score},明日青豆: +${signres.nextScore}\n` - $.setdata(1,'times') - if(firstcheck==undefined||firstcheck!=date){ - $.setdata(date,'signt'); - } - } else if (signres.status == 0) { - signresult = `【签到结果】重复`; - detail = ""; - if(runtimes!==undefined){ - $.setdata(`${parseInt(runtimes)+1}`,'times') - } - } - resolve() + detail = `【签到结果】成功 🎉 青豆: +${signres.score},明日青豆: +${signres.nextScore}\n`; + await comApp(); + } + resolve() }) }) } -function signInfo() { - return new Promise((resolve, reject) => { - const infourl = { - url: 'https://kd.youth.cn/TaskCenter/getSign', - headers: JSON.parse(signheaderVal), +function getArt() { + return new Promise((resolve, reject) =>{ + $.post(kdHost('WebApi/ArticleTop/listsNewTag'), async(error, resp, data) =>{ + artres = JSON.parse(data); + if (artres.status == 1) { + for (arts of artres.data.items) { + titlename = arts.title; + account = arts.account_id; + if (arts.status == "1") { + $.log("去转发文章"); + $.log(titlename + " ----- " + arts.account_name); + await artshare(arts.id); + break; + //await $.wait(500) + } } - $.post(infourl, (error, response, data) => { - signinfo = JSON.parse(data); - if (signinfo.status == 1) { - cash = signinfo.data.user.money - subTitle = `【收益总计】${signinfo.data.user.score}青豆 现金约${cash}元`; - nick = `账号: ${signinfo.data.user.nickname}`; - detail = `${signresult}(今天+${signinfo.data.sign_score}青豆) 已连签${signinfo.data.sign_day}天`; - detail +='\n<本次收益>:\n' - } else { - subTitle = `${signinfo.msg}`; - detail = ``; - } - resolve() - }) + } + resolve() }) + }) } -//开启打卡 -function punchCard() { +function artshare(artsid) { + return new Promise((resolve, reject) =>{ + $.post(kdHost('WebApi/ShareNew/getShareArticleReward', cookie + "&" + "article_id=" + artsid), async(error, resp, data) =>{ + shareres = JSON.parse(data); + if (shareres.status == 1) { + $.log("转发成功,共计转发" + shareres.data.items.share_num + "篇文章,获得青豆" + shareres.data.score) + } + resolve() + }) + }) +} + +function withDraw() { return new Promise((resolve, reject) => { const url = { - url: `${YOUTH_HOST}PunchCard/signUp?`, - headers: JSON.parse(signheaderVal), + url: withdrawUrl, + headers: { + 'User-Agent': 'KDApp/2.0.0 (iPhone; iOS 14.5; Scale/3.00)' + }, + body: withdrawBody, } - $.post(url, (error, response, data) => { - punchcardstart = JSON.parse(data); - if (punchcardstart.code == 1) { - detail += `【打卡报名】打卡报名${punchcardstart.msg} ✅ \n`; - $.log("每日报名打卡成功,报名时间:"+`${$.time('MM-dd HH:mm')}`) - resolve(); + $.post(url, (error, resp, data) => { + withDrawres = JSON.parse(data) + if (withDrawres.error_code == 0) { + detail += `【自动提现】提现${withdrawcash}元成功\n` + }else if(withDrawres.error_code == "10002"){ + $.log( `自动提现失败,${withDrawres.homeTime.text}`) + } else { + $.log( `自动提现失败,${withDrawres.message}`) } - else { - //detail += `【打卡报名】${punchcardstart.msg}\n` - // $.log(punchcardstart.msg) resolve() - } }) }) } +function CardStatus() { + return new Promise((resolve, reject) =>{ + $.get(kdHost('WebApi/PunchCard/getMainData?&' + cookie), async(error, resp, data) =>{ + punchcard = JSON.parse(data); + if (punchcard.code == 1) { + if (punchcard.data.user.status == 0 && $.time("HH") > "22") { + await punchCard() + } else if (punchcard.data.user.status == 2) { + $.log("每日打卡已报名,请每天早晨"+cardTime+"点运行打卡"); + detail += `【打卡报名】🔔 待明早${cardTime}点打卡\n` + } else if (punchcard.data.user.status == 3&&$.time("HH")==cardTime) { + $.log("打卡时间已到,去打卡"); + await endCard() + } else if (punchcard.data.user.status == 0) { + $.log("今日您未报名早起打卡"); + } + } else if (punchcard.code == 0) { + $.log("打卡申请失败" + data) + } + resolve(); + }) + }) +} + +function punchCard() { + return new Promise((resolve, reject) =>{ + $.post(kdHost('WebApi/PunchCard/signUp'), (error, response, data) =>{ + punchcardstart = JSON.parse(data); + if (punchcardstart.code == 1) { + detail += `【打卡报名】打卡报名${punchcardstart.msg}✅\n`; + $.log("每日报名打卡成功,报名时间:" + `${$.time('MM-dd HH:mm')}`) + } else { + detail += `【打卡报名】🔔${punchcardstart.msg}\n` + // $.log(punchcardstart.msg) + } + resolve(); + }) + }) +} + //结束打卡 function endCard() { - return new Promise((resolve, reject) => { - setTimeout(() => { - const url = { - url: `${YOUTH_HOST}PunchCard/doCard?`,headers: JSON.parse(signheaderVal), - } - $.post(url,async(error, response, data) => { - punchcardend = JSON.parse(data) - if (punchcardend.code == 1) { - detail += `【早起打卡】${punchcardend.data.card_time}${punchcardend.msg}✅\n` - $.log("早起打卡成功,打卡时间:"+`${punchcardend.data.card_time}`) - await Cardshare(); - } else if (punchcardend.code == 0) { - // TODO .不在打卡时间范围内 - //detail += `【早起打卡】${punchcardend.msg}\n` - // $.log("不在打卡时间范围内") - } - resolve() - }) - },s) - }) + return new Promise((resolve, reject) =>{ + $.post(kdHost('WebApi/PunchCard/doCard?'), async(error, resp, data) =>{ + punchcardend = JSON.parse(data); + if (punchcardend.code == 1) { + detail += `【早起打卡】${punchcardend.data.card_time}${punchcardend.msg}✅\n`; + $.log("早起打卡成功,打卡时间:" + `${punchcardend.data.card_time}`); + await $.wait(1000); + await Cardshare(); + } else if (punchcardend.code == 0) { + // TODO .不在打卡时间范围内 + detail += `【早起打卡】${punchcardend.msg}\n`; + // $.log("不在打卡时间范围内") + } + resolve() + }) + }) } //打卡分享 function Cardshare() { - return new Promise((resolve, reject) => { - const starturl = { - url: `${YOUTH_HOST}PunchCard/shareStart?`, - headers: JSON.parse(signheaderVal), - } - $.post(starturl, (error, response, data) => { - sharestart = JSON.parse(data) - //detail += `【打卡分享】${sharestart.msg}\n` - if (sharestart.code == 1) { - setTimeout(() => { - let endurl = { - url: `${YOUTH_HOST}PunchCard/shareEnd?`, - headers: JSON.parse(signheaderVal) - } - $.post(endurl, (error, response, data) => { - shareres = JSON.parse(data) - if (shareres.code == 1) { - detail += `+${shareres.data.score}青豆\n` - } else { - //detail += `【打卡分享】${shareres.msg}\n` - //$.log(`${shareres.msg}`) - } - resolve() - }) - },s*2); + return new Promise((resolve, reject) =>{ + $.post(kdHost('WebApi/PunchCard/shareStart?'), async(error, resp, data) =>{ + sharestart = JSON.parse(data); + //detail += `【打卡分享】${sharestart.msg}\n` + if (sharestart.code == 1) { + $.log("等待2s,去打卡分享") + await $.wait(2000); + $.post(kdHost('WebApi/PunchCard/shareEnd?'), (error, response, data) =>{ + shareres = JSON.parse(data); + if (shareres.code == 1) { + detail += ` +${shareres.data.score}青豆\n` + } else { + //detail += `【打卡分享】${shareres.msg}\n` + //$.log(`${shareres.msg}`) + } + resolve() + }) + } + }) + }) +} + + +function SevCont() { + return new Promise((resolve, reject) =>{ + $.post(kdHost('WebApi/PunchCard/luckdraw?'), async(error, resp, data) =>{ + let sevres = JSON.parse(data); + if (sevres.code == 1) { + detail += `【七日签到】 + ${sevres.data.score}青豆\n` + } else if (sevres.code == 0) { + //detail += `【七日签到】${sevres.msg}\n`; + //$.log(`七日签到:${sevres.msg}`) } + resolve() + }) + }) +} +function Census() { + return new Promise((resolve, reject) =>{ + $.post(kdHost('u/w6j7s'),async(error, resp, data) =>{ + await $.wait(500); + await int(); + resolve() }) }) } +function int() { + return new Promise((resolve, reject) =>{ + let url = { + url:"https://focus.youth.cn/v/oHi6Z/share?", + headers:kdHost().headers + } + $.post(url,(error, resp, data) =>{ + //$.log(resp) + resolve() + }) + }) +} //开启时段宝箱 function openbox() { - return new Promise((resolve, reject) => { - setTimeout(() => { - const url = { - url: `${YOUTH_HOST}invite/openHourRed`, - headers: JSON.parse(signheaderVal), - } - $.post(url, async(error, response, data) => { - boxres = JSON.parse(data) - if (boxres.code == 1) { - boxretime = boxres.data.time - $.setdata(boxretime, 'opbox') - detail += `【开启宝箱】+${boxres.data.score}青豆 下次奖励${boxres.data.time / 60}分钟\n` - await boxshare(); - }else{ - //detail += `【开启宝箱】${boxres.msg}\n` - // $.log(`${boxres.msg}`) - } - resolve() - }) - },s) + return new Promise((resolve, reject) =>{ + $.post(kdHost('WebApi/invite/openHourRed'), async(error, resp, data) =>{ + let boxres = JSON.parse(data); + if (boxres.code == 1) { + boxretime = boxres.data.time; + detail += '【时段宝箱】 +'+boxres.data.score+'青豆,'+boxres.data.time/60+'分钟后再次奖励\n'; + await boxshare(); + await getArt() + } else { + $.log('时段宝箱:'+ boxres.msg) + } + resolve() }) + }) } //宝箱分享 function boxshare() { - return new Promise((resolve, reject) => { - setTimeout(() => { - const url = { - url: `${YOUTH_HOST}invite/shareEnd`, - headers: JSON.parse(signheaderVal), - } - $.post(url, (error, response, data) => { - - shareres = JSON.parse(data) - if (shareres.code == 1) { - detail += `【宝箱分享】+${shareres.data.score}青豆\n` - }else{ - //detail += `【宝箱分享】${shareres.msg}\n` - //$.log(`${shareres.msg}`) - } - resolve() - }) - },s*2); + return new Promise((resolve, reject) =>{ + $.post(kdHost('WebApi/invite/shareEnd'), (error, resp, data) =>{ + let shareres = JSON.parse(data); + if (shareres.code == 1) { + //detail += `【宝箱分享】 + ${shareres.data.score}青豆\n` + } + resolve() }) + }) } -function Invitant() { - return new Promise((resolve, reject) => { - $.post({ url: `${YOUTH_HOST}User/fillCode`,headers: JSON.parse(signheaderVal),body: `{"code": "46746961"}` -}, (error, response, data) => - { - // $.log(`Invitdata:${data}`) - }) - resolve() - }) +function friendsign() { + return new Promise((resolve, reject) =>{ + $.get(kdHost('WebApi/ShareSignNew/getFriendActiveList'), async(error, resp, data) =>{ + let addsign = JSON.parse(data); + if (addsign.error_code == "0" && addsign.data.active_list.length > 0) { + friendsitem = addsign.data.active_list; + for (friends of friendsitem) { + if (friends.button == 1) { + await friendSign(friends.uid) + } + } + } + resolve() + }) + }) +} +function friendSign(uid) { + return new Promise((resolve, reject) =>{ + $.get(kdHost('WebApi/ShareSignNew/sendScoreV2?friend_uid='+uid), (error, resp, data) =>{ + let friendres = JSON.parse(data); + if (friendres.error_code == "0") { + detail += '【好友红包】+' + friendres.data[0].score + '个青豆\n'; + $.log('好友签到,我得红包 +'+friendres.data[0].score+'个青豆') + } + resolve() + }) + }) } //看视频奖励 function getAdVideo() { - return new Promise((resolve, reject) => { - const url = { - url: `https://kd.youth.cn/taskCenter/getAdVideoReward`, - headers: JSON.parse(signheaderVal), - body: 'type=taskCenter' - } - $.post(url, (error, response, data) => { - adVideores = JSON.parse(data) - if (adVideores.status == 1) { - detail += `【观看视频】+${adVideores.score}个青豆\n` - } - resolve() - }) + return new Promise((resolve, reject) =>{ + $.post(kdHost('taskCenter/getAdVideoReward','type=taskCenter'), (error, resp, data) =>{ + let adVideores = JSON.parse(data); + if (adVideores.status == 1) { + //detail += `【观看视频】+${adVideores.score}个青豆\n`; + $.log("观看视频广告" + adVideores.num + "次 +" + adVideores.score + "青豆") + } + resolve() }) + }) } +function recordAdVideo(acttype) { + return new Promise((resolve, reject) =>{ + $.get(kdHost('WebApi/NewTaskIos/recordNum?action='+acttype), async(error, resp, data) =>{ + try { + record = JSON.parse(data); + } catch(e) { + $.log("获取任务失败," + e) + } finally { + resolve() + } + }) + }) +} + +function batHost(api, body) { + return { + url: 'https://ios.baertt.com/v5/'+api, + headers: { + 'User-Agent': 'KDApp/2.0.0 (iPhone; iOS 14.5; Scale/3.00)', + 'Host': 'ios.baertt.com', + 'Content-Type': 'application/x-www-form-urlencoded' + }, + body: body + } +} + // 激励视频奖励 function gameVideo() { + return new Promise((resolve, reject) =>{ + $.post(batHost('Game/GameVideoReward.json', articbody), (error, resp, data) =>{ + gameres = JSON.parse(data); + if (gameres.success == true) { + //detail += `【激励视频】${gameres.items.score}\n` + $.log("激励视频 " + gameres.items.score) + } + resolve() + }) + }) +} + +function comApp() { return new Promise((resolve, reject) => { - const url = { - url: `https://ios.baertt.com/v5/Game/GameVideoReward.json`, - body: articlebodyVal, - } - $.post(url, (error, response, data) => { - gameres = JSON.parse(data) - if (gameres.success == true) { - detail += `【激励视频】${gameres.items.score}\n` - }else{ - if(gameres.error_code == "10003"){ - //detail += `【激励视频】${gameres.message}\n` - } + $.post(batHost('mission/msgRed.json',articbody), (error, resp, data) => { + comres = JSON.parse(data) + if (comres.success == true) { + detail += `【回访奖励】+${comres.items.score}个青豆\n` } resolve() }) }) } - //阅读奖励 function readArticle() { return new Promise((resolve, reject) => { - const url = { - url: `https://ios.baertt.com/v5/article/complete.json`, - headers: { - 'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148' - }, - body: articlebodyVal, - } - $.post(url, (error, response, data) => { + $.post(batHost('article/complete.json',articbody), (error, resp, data) => { + try{ readres = JSON.parse(data); - if (typeof readres.items.read_score === 'number') { + if(data.indexOf('read_score')>-1 && readres.items.read_score!=0) { detail += `【阅读奖励】+${readres.items.read_score}个青豆\n`; - } - //else if (readres.items.max_notice == '\u770b\u592a\u4e45\u4e86\uff0c\u63621\u7bc7\u8bd5\u8bd5') { - //detail += `【阅读奖励】看太久了,换1篇试试\n`; - // $.log(readres.items.max_notice)} + $.log(`阅读奖励 +${readres.items.read_score}个青豆`) + } else if (readres.items.max_notice == '看太久了,换1篇试试') { + //$.log(readres.items.max_notice) + } + } catch(e) { + $.logErr(e+resp); + } finally { + resolve() + } + }) + }) +} - resolve() - }) +function readTime() { + return new Promise((resolve, reject) =>{ + $.post(batHost('user/stay.json', timebody), (error, resp, data) =>{ + let timeres = JSON.parse(data); + if (timeres.error_code == 0) { + readtimes = timeres.time / 60; + detail += `【阅读时长】共计` + Math.floor(readtimes) + `分钟\n`; + $.log('阅读时长共计' + Math.floor(readtimes) + '分钟') + } else { + if (timeres.error_code == 200001) { + detail += '【阅读时长】❎ 未获取阅读时长请求\n'; + $.log(`阅读时长统计失败,原因:${timeres.msg}`) + } + } + resolve() }) + }) } -//惊喜红包 -function Articlered() { - return new Promise((resolve, reject) => { - const url = { - url: `https://ios.baertt.com/v5/article/red_packet.json`, - headers: { - 'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148' - }, - body: redpbodyVal, - } - $.post(url, (error, response, data) => { - redres = JSON.parse(data) - if (redres.success == true) { - detail += `【惊喜红包】+${redres.items.score}个青豆\n` - }else{ - if(redres.error_code == "100001"){ - //detail += `【惊喜红包】${redres.message}\n` - } - } - resolve() - }) + +function bonusTask() { + return new Promise((resolve, reject) =>{ + $.post(kdHost('WebApi/ShareNew/bereadExtraList'), async(error, resp, data) =>{ + extrares = JSON.parse(data); + if (extrares.status == 2) { + $.log("参数错误" + JSON.stringify(extrares)); + } else if (extrares.status == 1 && extrares.data.taskList[0].status == 1) { + timestatus = extrares.data.taskList[0].status; + timetitle = extrares.data.taskList[0].name; + $.log(timetitle + "可领取,去领青豆"); + await TimePacket(); + } + resolve() }) + }) } -function readTime() { - return new Promise((resolve, reject) => { - const url = { - url: `https://ios.baertt.com/v5/user/stay.json`, - headers: { - 'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148' - }, - body: timebodyVal, - } - $.post(url, (error, response, data) => { - let timeres = JSON.parse(data) - if (timeres.error_code == 0) { - readtimes = timeres.time / 60 - detail += `【阅读时长】共计` + Math.floor(readtimes) + `分钟\n` - } else { - if (timeres.error_code == 200001) { - detail += `【阅读时长】❎ 未获取阅读时长Cookie\n` - }else{ - detail += `【阅读时长】❎ ${timeres.msg}\n` - $.log(`阅读时长统计失败,原因:${timeres.msg}`) - } - } - resolve() - }) +function TimePacket() { + return new Promise((resolve, reject) =>{ + $.post(kdHost('WebApi/TimePacket/getReward', cookie), (error, resp, data) =>{ + let timeres = JSON.parse(data); + if (timeres.code == 1) { + $.log("获得" + timeres.data.score + "青豆"); + detail += "【" + timetitle + "】获得" + timeres.data.score + "青豆\n" + } else if (timeres.code == 0) { + $.log(timeres.msg) + } + resolve() }) + }) } //转盘任务 function rotary() { - const rotarbody = signheaderVal.split("&")[15] + '&' + signheaderVal.split("&")[8] - return new Promise((resolve, reject) => { - setTimeout(() => { - const time = new Date().getTime() - const url = { - url: `${YOUTH_HOST}RotaryTable/turnRotary?_=${time}`, - headers: JSON.parse(signheaderVal), - body: rotarbody - } - $.post(url,async (error, response, data) => { - rotaryres = JSON.parse(data) - if (rotaryres.status == 1) { - rotarytimes = rotaryres.data.remainTurn - detail += `【转盘抽奖】+${rotaryres.data.score}个青豆 剩余${rotaryres.data.remainTurn}次\n` - if (rotaryres.data.doubleNum != 0) { - await TurnDouble(); - } - } - if (rotaryres.code == 10010) { - rotarynum = ` 转盘${rotaryres.msg}🎉` - } - resolve(); - }) - }, s); - }) + return new Promise((resolve, reject) =>{ + $.post(kdHost(`WebApi/RotaryTable/turnRotary?_=${Date.now()}&`,cookie), async(error, resp, data) =>{ + try { + rotaryres = JSON.parse(data); + if (rotaryres.status == 0) { + rotarynum = `转盘${rotaryres.msg}🎉`; + $.log(rotarynum) + } else if (rotaryres.status == 1) { + $.log("等待" + s + "秒进行开始转盘任务"); + rotaryscore += rotaryres.data.score; + rotarytimes = rotaryres.data.remainTurn; + doubleTimes = rotaryres.data.doubleNum + $.log("进行"+parseInt(100-rotarytimes)+"次转盘,获得"+rotaryres.data.score+"青豆"); + if(rotaryres.data.score != 0&&doubleTimes!=0){ + $.log("等待10s,获得双倍青豆") + await $.wait(10000); + await TurnDouble(); + } + await rotaryCheck(); + } + } catch(e) { + $.logErr(e,resp); + } finally { + resolve() + } + }) + }) } //转盘宝箱判断 function rotaryCheck() { return new Promise(async(resolve) => { - if (rotaryres.code == 10010) { - return resolve(); - } let i = 0; while (i <= 3) { - if (100 - rotaryres.data.remainTurn == rotaryres.data.chestOpen[i].times) { + if (100 - rotarytimes >= rotaryres.data.chestOpen[i].times&&rotaryres.data.chestOpen[i].received==0) { await runRotary(i + 1) } i++; @@ -566,15 +692,9 @@ function rotaryCheck() { //开启宝箱 function runRotary(index) { return new Promise((resolve, reject) => { - const rotarbody = signheaderVal.split("&")[15] + '&' + signheaderVal.split("&")[8] + '&num=' + index; - const time = new Date().getTime(); - const url = { - url: `${YOUTH_HOST}RotaryTable/chestReward?_=${time}`, - headers: JSON.parse(signheaderVal), - body: rotarbody - } - $.post(url, (error, response, data) => { - const rotaryresp = JSON.parse(data); + const rotarbody = cookie + '&num=' + index; + $.post(kdHost(`WebApi/RotaryTable/chestReward?_=${Date.now()}&`,rotarbody), (error, resp, data) => { + let rotaryresp = JSON.parse(data); if (rotaryresp.status == 1) { detail += `【转盘宝箱${index}】+${rotaryresp.data.score}个青豆\n`; }else{ @@ -589,58 +709,55 @@ function runRotary(index) { //转盘双倍奖励 function TurnDouble() { - const rotarbody = signheaderVal.split("&")[15] + '&' + signheaderVal.split("&")[8] - return new Promise((resolve, reject) => { - setTimeout(() => { - let time = (new Date()).getTime() - const url = { - url: `${YOUTH_HOST}RotaryTable/toTurnDouble?_=${time}`,headers: JSON.parse(signheaderVal),body: rotarbody} - $.post(url, (error, response, data) => { - Doubleres = JSON.parse(data) - if (Doubleres.status == 1) { - detail += `【转盘双倍】+${Doubleres.data.score1}青豆 剩余${rotaryres.data.doubleNum}次\n` - }else{ - //detail += `【转盘双倍】失败 ${Doubleres.msg}\n` - - } - }) - resolve() - },s) + return new Promise((resolve, reject) =>{ + $.post(kdHost(`WebApi/RotaryTable/toTurnDouble?_=${Date.now()}&`,cookie), (error, resp, data) =>{ + try { + let Doubleres = JSON.parse(data); + if (Doubleres.data.is_double == 1) { + $.log("获得双倍青豆+" + Doubleres.data.score1); + doublerotary += Doubleres.data.score + } + } catch(e) { + $.logErr(e, resp); + } finally { + resolve() + } }) + }) } function earningsInfo() { - return new Promise((resolve, reject) => { - setTimeout(() => { - const url = { - url: `https://kd.youth.cn/wap/user/balance?${JSON.parse(signheaderVal)['Referer'].split("?")[1]}`, - headers: JSON.parse(signheaderVal), - } - $.get(url, (error, response, data) => { - infores = JSON.parse(data) - if (infores.status == 0) { - detail += `<收益统计>:\n` - for (i = 0; i < infores.history[0].group.length; i++) { - detail += '【' + infores.history[0].group[i].name + '】' + infores.history[0].group[i].money + '个青豆\n' - } - detail += '<今日合计>: ' + infores.history[0].score + " 青豆" - } - resolve() - }) - },s) + return new Promise((resolve, reject) =>{ + $.get(kdHost(`wap/user/balance?`+cookie), (error, response, data) =>{ + infores = JSON.parse(data); + if (infores.status == 0) { + detail += '<收益统计> :\n' + for (i = 0; i < infores.history[0].group.length; i++) { + detail += '【' + infores.history[0].group[i].name + '】' + infores.history[0].group[i].money + '个青豆\n' + } + detail += '<今日合计>: ' + infores.history[0].score + " 青豆" + } + resolve() }) + }) } async function showmsg() { - if (rotaryres.status == 1 && rotarytimes >= 97) { - $.msg($.name + " " + nick, subTitle, detail) //默认前三次为通知 + if ($.isNode() && rotaryres.status !== 0) { + if (rotarytimes && (100 - rotarytimes) % 95 == 0 && cash >= 10) { + await notify.sendNotify($.name + " " + nick, "您的余额约为" + cash + "元,已可以提现" + '\n' + `【收益总计】${signinfo.data.user.score}青豆现金约${cash}元\n${detail}`) + } + } else if (rotaryres.status == 1 && rotarytimes >= 97) { + $.msg($.name + " " + nick, subTitle, detail) //默认前三次为通知 }else if (rotaryres.status == 1 && rotarytimes % notifyInterval == 0) { $.msg($.name + " " + nick, subTitle, detail) //转盘次数/间隔整除时通知; }else if (rotaryres.code == 10010 && notifyInterval != 0) { - rotarynum = ` 转盘${rotaryres.msg}🎉` + //rotarynum = ` 转盘${rotaryres.msg}🎉` $.msg($.name+" "+nick+" "+rotarynum,subTitle,detail)//任务全部完成且通知间隔不为0时通知; } else { - console.log(`【收益总计】${signinfo.data.user.score}青豆 现金约${cash}元\n`+ detail) + console.log(`\n【收益总计】${totalscore}青豆 现金约${cash}元\n`+ detail) } } -function Env(t,e){class s{constructor(t){this.env=t}send(t,e="GET"){t="string"==typeof t?{url:t}:t;let s=this.get;return"POST"===e&&(s=this.post),new Promise((e,i)=>{s.call(this,t,(t,s,r)=>{t?i(t):e(s)})})}get(t){return this.send.call(this.env,t)}post(t){return this.send.call(this.env,t,"POST")}}return new class{constructor(t,e){this.name=t,this.http=new s(this),this.data=null,this.dataFile="box.dat",this.logs=[],this.isMute=!1,this.isNeedRewrite=!1,this.logSeparator="\n",this.startTime=(new Date).getTime(),Object.assign(this,e),this.log("",`\ud83d\udd14${this.name}, \u5f00\u59cb!`)}isNode(){return"undefined"!=typeof module&&!!module.exports}isQuanX(){return"undefined"!=typeof $task}isSurge(){return"undefined"!=typeof $httpClient&&"undefined"==typeof $loon}isLoon(){return"undefined"!=typeof $loon}toObj(t,e=null){try{return JSON.parse(t)}catch{return e}}toStr(t,e=null){try{return JSON.stringify(t)}catch{return e}}getjson(t,e){let s=e;const i=this.getdata(t);if(i)try{s=JSON.parse(this.getdata(t))}catch{}return s}setjson(t,e){try{return this.setdata(JSON.stringify(t),e)}catch{return!1}}getScript(t){return new Promise(e=>{this.get({url:t},(t,s,i)=>e(i))})}runScript(t,e){return new Promise(s=>{let i=this.getdata("@chavy_boxjs_userCfgs.httpapi");i=i?i.replace(/\n/g,"").trim():i;let r=this.getdata("@chavy_boxjs_userCfgs.httpapi_timeout");r=r?1*r:20,r=e&&e.timeout?e.timeout:r;const[o,h]=i.split("@"),a={url:`http://${h}/v1/scripting/evaluate`,body:{script_text:t,mock_type:"cron",timeout:r},headers:{"X-Key":o,Accept:"*/*"}};this.post(a,(t,e,i)=>s(i))}).catch(t=>this.logErr(t))}loaddata(){if(!this.isNode())return{};{this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(this.dataFile),e=this.path.resolve(process.cwd(),this.dataFile),s=this.fs.existsSync(t),i=!s&&this.fs.existsSync(e);if(!s&&!i)return{};{const i=s?t:e;try{return JSON.parse(this.fs.readFileSync(i))}catch(t){return{}}}}}writedata(){if(this.isNode()){this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(this.dataFile),e=this.path.resolve(process.cwd(),this.dataFile),s=this.fs.existsSync(t),i=!s&&this.fs.existsSync(e),r=JSON.stringify(this.data);s?this.fs.writeFileSync(t,r):i?this.fs.writeFileSync(e,r):this.fs.writeFileSync(t,r)}}lodash_get(t,e,s){const i=e.replace(/\[(\d+)\]/g,".$1").split(".");let r=t;for(const t of i)if(r=Object(r)[t],void 0===r)return s;return r}lodash_set(t,e,s){return Object(t)!==t?t:(Array.isArray(e)||(e=e.toString().match(/[^.[\]]+/g)||[]),e.slice(0,-1).reduce((t,s,i)=>Object(t[s])===t[s]?t[s]:t[s]=Math.abs(e[i+1])>>0==+e[i+1]?[]:{},t)[e[e.length-1]]=s,t)}getdata(t){let e=this.getval(t);if(/^@/.test(t)){const[,s,i]=/^@(.*?)\.(.*?)$/.exec(t),r=s?this.getval(s):"";if(r)try{const t=JSON.parse(r);e=t?this.lodash_get(t,i,""):e}catch(t){e=""}}return e}setdata(t,e){let s=!1;if(/^@/.test(e)){const[,i,r]=/^@(.*?)\.(.*?)$/.exec(e),o=this.getval(i),h=i?"null"===o?null:o||"{}":"{}";try{const e=JSON.parse(h);this.lodash_set(e,r,t),s=this.setval(JSON.stringify(e),i)}catch(e){const o={};this.lodash_set(o,r,t),s=this.setval(JSON.stringify(o),i)}}else s=this.setval(t,e);return s}getval(t){return this.isSurge()||this.isLoon()?$persistentStore.read(t):this.isQuanX()?$prefs.valueForKey(t):this.isNode()?(this.data=this.loaddata(),this.data[t]):this.data&&this.data[t]||null}setval(t,e){return this.isSurge()||this.isLoon()?$persistentStore.write(t,e):this.isQuanX()?$prefs.setValueForKey(t,e):this.isNode()?(this.data=this.loaddata(),this.data[e]=t,this.writedata(),!0):this.data&&this.data[e]||null}initGotEnv(t){this.got=this.got?this.got:require("got"),this.cktough=this.cktough?this.cktough:require("tough-cookie"),this.ckjar=this.ckjar?this.ckjar:new this.cktough.CookieJar,t&&(t.headers=t.headers?t.headers:{},void 0===t.headers.Cookie&&void 0===t.cookieJar&&(t.cookieJar=this.ckjar))}get(t,e=(()=>{})){t.headers&&(delete t.headers["Content-Type"],delete t.headers["Content-Length"]),this.isSurge()||this.isLoon()?(this.isSurge()&&this.isNeedRewrite&&(t.headers=t.headers||{},Object.assign(t.headers,{"X-Surge-Skip-Scripting":!1})),$httpClient.get(t,(t,s,i)=>{!t&&s&&(s.body=i,s.statusCode=s.status),e(t,s,i)})):this.isQuanX()?(this.isNeedRewrite&&(t.opts=t.opts||{},Object.assign(t.opts,{hints:!1})),$task.fetch(t).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>e(t))):this.isNode()&&(this.initGotEnv(t),this.got(t).on("redirect",(t,e)=>{try{if(t.headers["set-cookie"]){const s=t.headers["set-cookie"].map(this.cktough.Cookie.parse).toString();this.ckjar.setCookieSync(s,null),e.cookieJar=this.ckjar}}catch(t){this.logErr(t)}}).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>{const{message:s,response:i}=t;e(s,i,i&&i.body)}))}post(t,e=(()=>{})){if(t.body&&t.headers&&!t.headers["Content-Type"]&&(t.headers["Content-Type"]="application/x-www-form-urlencoded"),t.headers&&delete t.headers["Content-Length"],this.isSurge()||this.isLoon())this.isSurge()&&this.isNeedRewrite&&(t.headers=t.headers||{},Object.assign(t.headers,{"X-Surge-Skip-Scripting":!1})),$httpClient.post(t,(t,s,i)=>{!t&&s&&(s.body=i,s.statusCode=s.status),e(t,s,i)});else if(this.isQuanX())t.method="POST",this.isNeedRewrite&&(t.opts=t.opts||{},Object.assign(t.opts,{hints:!1})),$task.fetch(t).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>e(t));else if(this.isNode()){this.initGotEnv(t);const{url:s,...i}=t;this.got.post(s,i).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>{const{message:s,response:i}=t;e(s,i,i&&i.body)})}}time(t){let e={"M+":(new Date).getMonth()+1,"d+":(new Date).getDate(),"H+":(new Date).getHours(),"m+":(new Date).getMinutes(),"s+":(new Date).getSeconds(),"q+":Math.floor(((new Date).getMonth()+3)/3),S:(new Date).getMilliseconds()};/(y+)/.test(t)&&(t=t.replace(RegExp.$1,((new Date).getFullYear()+"").substr(4-RegExp.$1.length)));for(let s in e)new RegExp("("+s+")").test(t)&&(t=t.replace(RegExp.$1,1==RegExp.$1.length?e[s]:("00"+e[s]).substr((""+e[s]).length)));return t}msg(e=t,s="",i="",r){const o=t=>{if(!t)return t;if("string"==typeof t)return this.isLoon()?t:this.isQuanX()?{"open-url":t}:this.isSurge()?{url:t}:void 0;if("object"==typeof t){if(this.isLoon()){let e=t.openUrl||t.url||t["open-url"],s=t.mediaUrl||t["media-url"];return{openUrl:e,mediaUrl:s}}if(this.isQuanX()){let e=t["open-url"]||t.url||t.openUrl,s=t["media-url"]||t.mediaUrl;return{"open-url":e,"media-url":s}}if(this.isSurge()){let e=t.url||t.openUrl||t["open-url"];return{url:e}}}};this.isMute||(this.isSurge()||this.isLoon()?$notification.post(e,s,i,o(r)):this.isQuanX()&&$notify(e,s,i,o(r)));let h=["","==============\ud83d\udce3\u7cfb\u7edf\u901a\u77e5\ud83d\udce3=============="];h.push(e),s&&h.push(s),i&&h.push(i),console.log(h.join("\n")),this.logs=this.logs.concat(h)}log(...t){t.length>0&&(this.logs=[...this.logs,...t]),console.log(t.join(this.logSeparator))}logErr(t,e){const s=!this.isSurge()&&!this.isQuanX()&&!this.isLoon();s?this.log("",`\u2757\ufe0f${this.name}, \u9519\u8bef!`,t.stack):this.log("",`\u2757\ufe0f${this.name}, \u9519\u8bef!`,t)}wait(t){return new Promise(e=>setTimeout(e,t))}done(t={}){const e=(new Date).getTime(),s=(e-this.startTime)/1e3;this.log("",`\ud83d\udd14${this.name}, \u7ed3\u675f! \ud83d\udd5b ${s} \u79d2`),this.log(),(this.isSurge()||this.isQuanX()||this.isLoon())&&$done(t)}}(t,e)} \ No newline at end of file +function GetCookie(){if($request&&$request.method!=`OPTIONS`&&$request.url.match(/\/NewTaskIos\/getTaskList/)){RefererVal=$request.headers.Referer;signheaderVal=RefererVal.match(/&uid=\d+/)+RefererVal.match(/&cookie=[_a-zA-Z0-9-]+/)+RefererVal.match(/&cookie_id=[a-zA-Z0-9]+/);if(signheaderVal)$.setdata(signheaderVal,'youthheader_zq');$.log(`${$.name}获取Cookie: 成功, signheaderVal: $}`);$.msg($.name,`获取Cookie: 成功🎉`,``)}else if($request&&$request.method!=`OPTIONS`&&$request.url.match(/\/article\/info\/get/)){articlebodyVal=$request.url.split("?")[1];if(articlebodyVal)$.setdata(articlebodyVal,'read_zq');$.log(`${$.name}获取阅读: 成功, articbody: ${articlebodyVal}`);$.msg($.name,`获取阅读请求: 成功🎉`,``)}else if($request&&$request.method!=`OPTIONS`&&$request.url.match(/\/v5\/user\/stay/)){const timebodyVal=$request.body;if(timebodyVal)$.setdata(timebodyVal,'readtime_zq');$.log(`${$.name}获取阅读时长: 成功, timebodyVal: ${timebodyVal}`);$.msg($.name,`获取阅读时长: 成功🎉`,``)}else if($request&&$request.method!=`OPTIONS`&&$request.url.match(/\/withdraw\d?\.json/)){const withdrawVal=$request.body;const withdrawUrl=$request.url;if(withdrawVal)$.setdata(withdrawVal,'cashbody_zq');if(withdrawUrl)$.setdata(withdrawUrl,'cashurl_zq');$.log(`${$.name}, 获取提现请求: 成功, withdrawUrl: ${withdrawUrl}`);$.log(`${$.name}, 获取提现请求: 成功, withdrawBody: ${withdrawVal}`);$.msg($.name,`获取提现请求: 成功🎉`,``)}} + +function Env(t,e){class s{constructor(t){this.env=t}send(t,e="GET"){t="string"==typeof t?{url:t}:t;let s=this.get;return"POST"===e&&(s=this.post),new Promise((e,i)=>{s.call(this,t,(t,s,r)=>{t?i(t):e(s)})})}get(t){return this.send.call(this.env,t)}post(t){return this.send.call(this.env,t,"POST")}}return new class{constructor(t,e){this.name=t,this.http=new s(this),this.data=null,this.dataFile="box.dat",this.logs=[],this.isMute=!1,this.isNeedRewrite=!1,this.logSeparator="\n",this.startTime=(new Date).getTime(),Object.assign(this,e),this.log("",`\ud83d\udd14${this.name}, \u5f00\u59cb!`)}isNode(){return"undefined"!=typeof module&&!!module.exports}isQuanX(){return"undefined"!=typeof $task}isSurge(){return"undefined"!=typeof $httpClient&&"undefined"==typeof $loon}isLoon(){return"undefined"!=typeof $loon}toObj(t,e=null){try{return JSON.parse(t)}catch{return e}}toStr(t,e=null){try{return JSON.stringify(t)}catch{return e}}getjson(t,e){let s=e;const i=this.getdata(t);if(i)try{s=JSON.parse(this.getdata(t))}catch{}return s}setjson(t,e){try{return this.setdata(JSON.stringify(t),e)}catch{return!1}}getScript(t){return new Promise(e=>{this.get({url:t},(t,s,i)=>e(i))})}runScript(t,e){return new Promise(s=>{let i=this.getdata("@chavy_boxjs_userCfgs.httpapi");i=i?i.replace(/\n/g,"").trim():i;let r=this.getdata("@chavy_boxjs_userCfgs.httpapi_timeout");r=r?1*r:20,r=e&&e.timeout?e.timeout:r;const[o,h]=i.split("@"),a={url:`http://${h}/v1/scripting/evaluate`,body:{script_text:t,mock_type:"cron",timeout:r},headers:{"X-Key":o,Accept:"*/*"}};this.post(a,(t,e,i)=>s(i))}).catch(t=>this.logErr(t))}loaddata(){if(!this.isNode())return{};{this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(this.dataFile),e=this.path.resolve(process.cwd(),this.dataFile),s=this.fs.existsSync(t),i=!s&&this.fs.existsSync(e);if(!s&&!i)return{};{const i=s?t:e;try{return JSON.parse(this.fs.readFileSync(i))}catch(t){return{}}}}}writedata(){if(this.isNode()){this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(this.dataFile),e=this.path.resolve(process.cwd(),this.dataFile),s=this.fs.existsSync(t),i=!s&&this.fs.existsSync(e),r=JSON.stringify(this.data);s?this.fs.writeFileSync(t,r):i?this.fs.writeFileSync(e,r):this.fs.writeFileSync(t,r)}}lodash_get(t,e,s){const i=e.replace(/\[(\d+)\]/g,".$1").split(".");let r=t;for(const t of i)if(r=Object(r)[t],void 0===r)return s;return r}lodash_set(t,e,s){return Object(t)!==t?t:(Array.isArray(e)||(e=e.toString().match(/[^.[\]]+/g)||[]),e.slice(0,-1).reduce((t,s,i)=>Object(t[s])===t[s]?t[s]:t[s]=Math.abs(e[i+1])>>0==+e[i+1]?[]:{},t)[e[e.length-1]]=s,t)}getdata(t){let e=this.getval(t);if(/^@/.test(t)){const[,s,i]=/^@(.*?)\.(.*?)$/.exec(t),r=s?this.getval(s):"";if(r)try{const t=JSON.parse(r);e=t?this.lodash_get(t,i,""):e}catch(t){e=""}}return e}setdata(t,e){let s=!1;if(/^@/.test(e)){const[,i,r]=/^@(.*?)\.(.*?)$/.exec(e),o=this.getval(i),h=i?"null"===o?null:o||"{}":"{}";try{const e=JSON.parse(h);this.lodash_set(e,r,t),s=this.setval(JSON.stringify(e),i)}catch(e){const o={};this.lodash_set(o,r,t),s=this.setval(JSON.stringify(o),i)}}else s=this.setval(t,e);return s}getval(t){return this.isSurge()||this.isLoon()?$persistentStore.read(t):this.isQuanX()?$prefs.valueForKey(t):this.isNode()?(this.data=this.loaddata(),this.data[t]):this.data&&this.data[t]||null}setval(t,e){return this.isSurge()||this.isLoon()?$persistentStore.write(t,e):this.isQuanX()?$prefs.setValueForKey(t,e):this.isNode()?(this.data=this.loaddata(),this.data[e]=t,this.writedata(),!0):this.data&&this.data[e]||null}initGotEnv(t){this.got=this.got?this.got:require("got"),this.cktough=this.cktough?this.cktough:require("tough-cookie"),this.ckjar=this.ckjar?this.ckjar:new this.cktough.CookieJar,t&&(t.headers=t.headers?t.headers:{},void 0===t.headers.Cookie&&void 0===t.cookieJar&&(t.cookieJar=this.ckjar))}get(t,e=(()=>{})){t.headers&&(delete t.headers["Content-Type"],delete t.headers["Content-Length"]),this.isSurge()||this.isLoon()?(this.isSurge()&&this.isNeedRewrite&&(t.headers=t.headers||{},Object.assign(t.headers,{"X-Surge-Skip-Scripting":!1})),$httpClient.get(t,(t,s,i)=>{!t&&s&&(s.body=i,s.statusCode=s.status),e(t,s,i)})):this.isQuanX()?(this.isNeedRewrite&&(t.opts=t.opts||{},Object.assign(t.opts,{hints:!1})),$task.fetch(t).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>e(t))):this.isNode()&&(this.initGotEnv(t),this.got(t).on("redirect",(t,e)=>{try{if(t.headers["set-cookie"]){const s=t.headers["set-cookie"].map(this.cktough.Cookie.parse).toString();this.ckjar.setCookieSync(s,null),e.cookieJar=this.ckjar}}catch(t){this.logErr(t)}}).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>{const{message:s,response:i}=t;e(s,i,i&&i.body)}))}post(t,e=(()=>{})){if(t.body&&t.headers&&!t.headers["Content-Type"]&&(t.headers["Content-Type"]="application/x-www-form-urlencoded"),t.headers&&delete t.headers["Content-Length"],this.isSurge()||this.isLoon())this.isSurge()&&this.isNeedRewrite&&(t.headers=t.headers||{},Object.assign(t.headers,{"X-Surge-Skip-Scripting":!1})),$httpClient.post(t,(t,s,i)=>{!t&&s&&(s.body=i,s.statusCode=s.status),e(t,s,i)});else if(this.isQuanX())t.method="POST",this.isNeedRewrite&&(t.opts=t.opts||{},Object.assign(t.opts,{hints:!1})),$task.fetch(t).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>e(t));else if(this.isNode()){this.initGotEnv(t);const{url:s,...i}=t;this.got.post(s,i).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>{const{message:s,response:i}=t;e(s,i,i&&i.body)})}}time(t){let e={"M+":(new Date).getMonth()+1,"d+":(new Date).getDate(),"H+":(new Date).getHours(),"m+":(new Date).getMinutes(),"s+":(new Date).getSeconds(),"q+":Math.floor(((new Date).getMonth()+3)/3),S:(new Date).getMilliseconds()};/(y+)/.test(t)&&(t=t.replace(RegExp.$1,((new Date).getFullYear()+"").substr(4-RegExp.$1.length)));for(let s in e)new RegExp("("+s+")").test(t)&&(t=t.replace(RegExp.$1,1==RegExp.$1.length?e[s]:("00"+e[s]).substr((""+e[s]).length)));return t}msg(e=t,s="",i="",r){const o=t=>{if(!t)return t;if("string"==typeof t)return this.isLoon()?t:this.isQuanX()?{"open-url":t}:this.isSurge()?{url:t}:void 0;if("object"==typeof t){if(this.isLoon()){let e=t.openUrl||t.url||t["open-url"],s=t.mediaUrl||t["media-url"];return{openUrl:e,mediaUrl:s}}if(this.isQuanX()){let e=t["open-url"]||t.url||t.openUrl,s=t["media-url"]||t.mediaUrl;return{"open-url":e,"media-url":s}}if(this.isSurge()){let e=t.url||t.openUrl||t["open-url"];return{url:e}}}};this.isMute||(this.isSurge()||this.isLoon()?$notification.post(e,s,i,o(r)):this.isQuanX()&&$notify(e,s,i,o(r)));let h=["","==============\ud83d\udce3\u7cfb\u7edf\u901a\u77e5\ud83d\udce3=============="];h.push(e),s&&h.push(s),i&&h.push(i),console.log(h.join("\n")),this.logs=this.logs.concat(h)}log(...t){t.length>0&&(this.logs=[...this.logs,...t]),console.log(t.join(this.logSeparator))}logErr(t,e){const s=!this.isSurge()&&!this.isQuanX()&&!this.isLoon();s?this.log("",`\u2757\ufe0f${this.name}, \u9519\u8bef!`,t.stack):this.log("",`\u2757\ufe0f${this.name}, \u9519\u8bef!`,t)}wait(t){return new Promise(e=>setTimeout(e,t))}done(t={}){const e=(new Date).getTime(),s=(e-this.startTime)/1e3;this.log("",`\ud83d\udd14${this.name}, \u7ed3\u675f! \ud83d\udd5b ${s} \u79d2`),this.log(),(this.isSurge()||this.isQuanX()||this.isLoon())&&$done(t)}}(t,e)} diff --git a/Task/youth_env.js b/Task/youth_env.js new file mode 100644 index 0000000000..d5cff58cf3 --- /dev/null +++ b/Task/youth_env.js @@ -0,0 +1,21 @@ + if (process.env.YOUTH_HEADER && process.env.YOUTH_HEADER.indexOf('#') > -1) { + cookieYouth = process.env.YOUTH_HEADER.split('#'); + } else if (process.env.YOUTH_HEADER && process.env.YOUTH_HEADER.indexOf('\n') > -1) { + cookieYouth = process.env.YOUTH_HEADER.split('\n'); + } else { + cookieYouth = [process.env.YOUTH_HEADER] + }; + if (process.env.YOUTH_ARTBODY && process.env.YOUTH_ARTBODY.indexOf('&') > -1) { + ARTBODYs = process.env.YOUTH_ARTBODY.split('&'); + } else if (process.env.YOUTH_ARTBODY && process.env.YOUTH_ARTBODY.indexOf('\n') > -1) { + ARTBODYs = process.env.YOUTH_ARTBODY.split('\n'); + } else { + ARTBODYs = [process.env.YOUTH_ARTBODY] + }; + if (process.env.YOUTH_TIME && process.env.YOUTH_TIME.indexOf('&') > -1) { + READTIME = process.env.YOUTH_TIME.split('&'); + } else if (process.env.YOUTH_TIME && process.env.YOUTH_TIME.indexOf('\n') > -1) { + READTIME = process.env.YOUTH_TIME.split('\n'); + } else { + READTIME = [process.env.YOUTH_TIME] + } \ No newline at end of file diff --git a/Task/jingxi.js b/Task/youth_gain.js similarity index 55% rename from Task/jingxi.js rename to Task/youth_gain.js index fae87ebc4d..adf4b054b9 100644 --- a/Task/jingxi.js +++ b/Task/youth_gain.js @@ -1,204 +1,167 @@ /* -更新时间:10-09 20:05 -本脚本为京东旗下京喜app签到脚本 -本脚本使用京东公共Cooike,支持双账号,获取方法请查看NobyDa大佬脚本说明 +更新时间: 2020-12-16 22:06 +Github Actions使用方法见[@lxk0301](https://raw.githubusercontent.com/lxk0301/scripts/master/githubAction.md) 使用方法大同小异 -[task_local] -0 9 * * * https://raw.githubusercontent.com/Sunert/Scripts/master/Task/jingxi.js +中青看点浏览赚任务,手动完成任务,获取请求体,支持boxjs及Github Actions,多请求用"&"分开,支持自动获取请求 + +https:\/\/ios\.baertt\.com\/v5\/task\/browse_(start|end)\.json url script-request-body youth_gain.js + + +多个请求体时用'&'号或者换行隔开" ‼️ -~~~~~~~~~~~~~~~~ -[MITM] -hostname = wq.jd.com -~~~~~~~~~~~~~~~~ */ -const $ = new Env('京喜'); -let cookiesArr = [], cookie = '', signresult,todaypoint = 0; + +const $ = new Env("中青看点浏览赚") const notify = $.isNode() ? require('./sendNotify') : ''; -const jdCookieNode = $.isNode() ? require('./jdCookie.js') : ''; +let StartBody = [], EndBody = [], gainscore = Number(); +let startArr = [],endArr = []; +let startbodys = $.getdata('youth_start') +let endbodys = $.getdata('youth_end') +if (isGetCookie = typeof $request !==`undefined`) { + GetCookie(); + $.done() +} if ($.isNode()) { - Object.keys(jdCookieNode).forEach((item) => { - cookiesArr.push(jdCookieNode[item]) - }) + if (process.env.YOUTH_START && process.env.YOUTH_START.indexOf('&') > -1) { + StartBody = process.env.YOUTH_START.split('&'); + }else { + StartBody = process.env.YOUTH_START.split() + }; + if (process.env.YOUTH_END && process.env.YOUTH_END.indexOf('&') > -1) { + EndBody = process.env.YOUTH_END.split('&'); + } else { + EndBody = process.env.YOUTH_END.split() + } } else { - cookiesArr.push($.getdata('CookieJD')); - cookiesArr.push($.getdata('CookieJD2')) + StartBody = $.getdata('youth_start').split('&'); + EndBody = $.getdata('youth_end').split('&'); } -!(async () => { - if (!cookiesArr[0]) { - $.msg($.name, '【提示】请先获取京东账号一cookie\n直接使用NobyDa的京东签到获取', 'https://bean.m.jd.com/', {"open-url": "https://bean.m.jd.com/"}); - return; - } - for (let i = 0; i < cookiesArr.length; i++) { - if (cookiesArr[i]) { - cookie = cookiesArr[i]; - UserName = decodeURIComponent(cookie.match(/pt_pin=(\w+)/) && cookie.match(/pt_pin=(\w+)/)[1]) - $.index = i + 1; - console.log(`\n开始【京东账号${$.index}】${UserName}\n`); - await getsign(); - await Tasklist(); - await doublesign(); - await coininfo(); - await showmsg(); - if ($.isNode()){ - await notify.sendNotify($.name + " 账号昵称:" + nickname, $.sub+`\n`+$.desc) - } - } - } -})() - .catch((e) => $.logErr(e)) - .finally(() => $.done()) - -function getsign() { - return new Promise((resolve) => { - const signurl = { - url: 'https://wq.jd.com/pgcenter/sign/UserSignOpr?g_login_type=1', - headers: { - "Content-Type": "application/x-www-form-urlencoded", - Cookie: cookie, - Referer: "https://wqsh.jd.com/pingou/taskcenter/index.html" - }, - } - $.get(signurl, (err, resp, data) => { - signres = JSON.parse(data) - if (signres.retCode == '0') { - nickname = signres.data.nickname - totalpoints = signres.data.pgAmountTotal - signdays = "已签" + signres.data.signDays + "天" - if (signres.data.signStatus == 0) { - signresult = "签到成功" - signdays += " 今日获得" + data.match(/[0-9]+/g)[4] + "积分" + Object.keys(StartBody).forEach((item) => { + if (StartBody[item]) { + startArr.push(StartBody[item]) + } + }) - } else if (signres.data.signStatus == 1) { - signresult = "签到重复" + Object.keys(EndBody).forEach((item) => { + if (EndBody[item]) { + endArr.push(EndBody[item]) } - } else if (signres.retCode == '30003') { - $.msg($.name, '【提示】京东cookie已失效,请重新登录获取', 'https://bean.m.jd.com/', {"open-url": "https://bean.m.jd.com/"}); - } - resolve() }) - }) +if ($.isNode()) { + timeZone = new Date().getTimezoneOffset() / 60; + timestamp = Date.now()+ (8+timeZone) * 60 * 60 * 1000; + bjTime = new Date(timestamp).toLocaleString('zh',{hour12:false,timeZoneName: 'long'}); + console.log(`\n === 脚本执行 ${bjTime} ===\n`); } - -function coininfo() { - return new Promise((resolve, reject) => { - const coinurl = { - url: "https://wq.jd.com/pgcenter/sign/QueryPGDetail?sceneval=2", - headers: { - "Content-Type": "application/x-www-form-urlencoded", - Cookie: cookie, - Referer: "https://jddx.jd.com/m/jddnew/money/index.html" - } + !(async () => { + if (!startArr[0]) { + console.log($.name, '【提示】请把抓包的请求体填入Github 的 Secrets 中,请以&隔开') + return; + } + console.log(`您共提供${startArr.length}次浏览赚任务`) + for (let i = 0; i < startArr.length; i++) { + if (startArr[i]) { + gainStartbody = startArr[i]; + gainEndbody = endArr[i] + $.index = i + 1; + console.log(`-------------------------\n\n开始中青看点浏览赚第${$.index}次任务`) } - $.get(coinurl, (err, resp, data) => { - let coindata = JSON.parse(data), - localetime = new Date(new Date().toLocaleDateString()).getTime()/1000, - item = coindata.data.list; - daytotal = Number(); - var i = 0; - for(i=0;i=localetime;i++){ - if (item[i].activeId === '10000'){ - todaypoint = item[i].accountValue - }; - if (item[i].activeId ==='30000'){ - daytotal += item[i].accountValue - }; - } - resolve() - }) - }) + await GainStart(); + } + console.log(`-------------------------\n\n中青看点共完成${$.index}次任务,共计获得${gainscore}个青豆,浏览赚任务全部结束`); + $.msg($.name, `共完成${$.index}次任务`, `共计获得${gainscore}个青豆`) + if ($.isNode()){ + //await notify.sendNotify($.name,`共完成${$.index}次任务,\n共计获得${gainscore}个青豆` } +})() + .catch((e) => $.logErr(e)) + .finally(() => $.done()) -function Tasklist(taskid) { - return new Promise( (resolve) => { - const url = { - url: 'https://m.jingxi.com/pgcenter/task/QueryPgTaskCfgByType?&taskType=3', - headers: { - "Content-Type": "application/x-www-form-urlencoded", - Cookie: cookie, - Referer: "https://st.jingxi.com/pingou/task_center/task/index.html?jxsid=" - }, - } - $.get(url, async (err, resp, data) => { - totaskres = JSON.parse(data) - var item = totaskres.data.tasks; - let taskArr = []; - for (task of item) { - taskArr.push(task.taskId); - await dotask(task.taskId); - await taskFinish(task.taskId); - } - resolve() +function GainStart() { + return new Promise((resolve, reject) => { + let url = { + url: `https://ios.baertt.com/v5/task/browse_start.json`, + headers: { + 'User-Agent': 'KDApp/1.7.8 (iPhone; iOS 14.0; Scale/3.00)', + 'Content-Type': 'application/x-www-form-urlencoded' + }, + body: gainStartbody + }; + $.post(url, async(error, response, data) => { + let startres = JSON.parse(data); + if(startres.items.comtele_state ==0){ + $.log("任务开始,"+startres.items.banner_id+startres.message) + await $.wait(10000); + await GainEnd() + } else if(startres.items.comtele_state ==1){ + $.log("任务:"+startres.items.banner_id+"已完成,本次跳过") + await $.wait(2000); + } + resolve() + }) }) - }) } -function dotask(id) { - return new Promise((resolve) => { - const url = { - url: `https://m.jingxi.com/pgcenter/task/drawUserTask?sceneval=2&taskid=${id}`, - headers: { - "Content-Type": "application/x-www-form-urlencoded", - Cookie: cookie, - Referer: "https://st.jingxi.com/pingou/task_center/task/index.html?jxsid=" - } - } - $.get(url, (err, resp, data) => { - const task = JSON.parse(data) - //console.log(task) - resolve() +function GainEnd() { + return new Promise((resolve, reject) => { + let url = { + url: `https://ios.baertt.com/v5/task/browse_end.json`, + headers: { + 'User-Agent': 'KDApp/1.7.8 (iPhone; iOS 14.0; Scale/3.00)', + 'Content-Type': 'application/x-www-form-urlencoded' + }, + body: gainEndbody + }; + $.post(url, async(error, response, data) => { + let endres = JSON.parse(data); + if(endres.success==true){ + $.log("任务"+endres.items.banner_id+endres.message+",恭喜获得"+endres.items.score+"个青豆") + gainscore += Number(endres.items.score) + } else ( + $.log(endres.message) + ) + resolve() + }) }) - }) -} -function taskFinish(taskId) { - return new Promise((resolve) => { - const url = { - url: `https://m.jingxi.com/pgcenter/task/UserTaskFinish?sceneval=2&taskid=${taskId}&sceneval=2&g_login_type=1&g_ty=ls`, - headers: { - "Content-Type": "application/x-www-form-urlencoded", - Cookie: cookie, - Referer: "https://st.jingxi.com/pingou/task_center/task/index.html?jxsid=" - } - } - $.get(url, (err, resp, data) => { - const task = JSON.parse(data) - //console.log(task) - resolve() - }) - }) -} -function doublesign() { - return new Promise((resolve) => { - const doubleurl = { - url: 'https://m.jingxi.com/double_sign/IssueReward?sceneval=2&g_login_type=1&g_ty=ajax', - headers: { - "Content-Type": "application/x-www-form-urlencoded", - Cookie: cookie, - Referer: "https://st.jingxi.com/pingou/jxapp_double_signin/index.html?ptag=139037.2.1" - } - } - $.get(doubleurl, (err, resp, data) => { - doub = JSON.parse(data) - if (doub.retCode == 0) { - doubleres = " 双签成功 🧧+ " + doub.data.jd_amount / 100 + "元"; - $.log($.name + "" + doubleres) - } - resolve() - }) - }) } -function showmsg() { - return new Promise((resolve) => { - if(signresult){ - $.sub = "积分总计:" + totalpoints+" " + signresult - $.desc = signdays +doubleres+ '\n' + "今日签到得" + todaypoint + "个金币 共计" + (daytotal+todaypoint)+'个金币' - $.msg($.name + " 账号昵称:" + nickname, $.sub, $.desc) - } - resolve() - }) +function GetCookie() { +if ($request && $request.method != 'OPTIONS' && $request.url.match(/\/browse_start\.json/)) { + const startbodyVal = $request.body; + if(startbodys){ + if(startbodys.indexOf(startbodyVal)>-1){ + $.msg($.name,'阅读请求重复,本次跳过'); + return + }else if(startbodys.indexOf(startbodyVal)==-1) + { + startbodys += "&"+startbodyVal + } + } else { + startbodys = $request.body + } + $.setdata(startbodys,'youth_start') + $.log("看看赚开始请求: "+startbodyVal) + $.msg($.name,'获取开始请求成功'); + }; + +if ($request && $request.method != 'OPTIONS' && $request.url.match(/\/browse_end\.json/)) { + const endbodyVal = $request.body + if(endbodys){ + if(endbodys.indexOf(endbodyVal)>-1){ + $.msg($.name,'获取任务开始请求重复,本次跳过'); + return + } else if(endbodys.indexOf(endbodyVal)==-1){ + endbodys += "&"+endbodyVal + } + }else { + endbodys = $request.body + } + $.setdata(endbodys,'youth_end') + $.log("看看赚结束请求: "+endbodyVal) + $.msg($.name,'获取任务结束请求成功'); + } } -// prettier-ignore -function Env(t,e){class s{constructor(t){this.env=t}send(t,e="GET"){t="string"==typeof t?{url:t}:t;let s=this.get;return"POST"===e&&(s=this.post),new Promise((e,i)=>{s.call(this,t,(t,s,r)=>{t?i(t):e(s)})})}get(t){return this.send.call(this.env,t)}post(t){return this.send.call(this.env,t,"POST")}}return new class{constructor(t,e){this.name=t,this.http=new s(this),this.data=null,this.dataFile="box.dat",this.logs=[],this.isMute=!1,this.isNeedRewrite=!1,this.logSeparator="\n",this.startTime=(new Date).getTime(),Object.assign(this,e),this.log("",`\ud83d\udd14${this.name}, \u5f00\u59cb!`)}isNode(){return"undefined"!=typeof module&&!!module.exports}isQuanX(){return"undefined"!=typeof $task}isSurge(){return"undefined"!=typeof $httpClient&&"undefined"==typeof $loon}isLoon(){return"undefined"!=typeof $loon}toObj(t,e=null){try{return JSON.parse(t)}catch{return e}}toStr(t,e=null){try{return JSON.stringify(t)}catch{return e}}getjson(t,e){let s=e;const i=this.getdata(t);if(i)try{s=JSON.parse(this.getdata(t))}catch{}return s}setjson(t,e){try{return this.setdata(JSON.stringify(t),e)}catch{return!1}}getScript(t){return new Promise(e=>{this.get({url:t},(t,s,i)=>e(i))})}runScript(t,e){return new Promise(s=>{let i=this.getdata("@chavy_boxjs_userCfgs.httpapi");i=i?i.replace(/\n/g,"").trim():i;let r=this.getdata("@chavy_boxjs_userCfgs.httpapi_timeout");r=r?1*r:20,r=e&&e.timeout?e.timeout:r;const[o,h]=i.split("@"),a={url:`http://${h}/v1/scripting/evaluate`,body:{script_text:t,mock_type:"cron",timeout:r},headers:{"X-Key":o,Accept:"*/*"}};this.post(a,(t,e,i)=>s(i))}).catch(t=>this.logErr(t))}loaddata(){if(!this.isNode())return{};{this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(this.dataFile),e=this.path.resolve(process.cwd(),this.dataFile),s=this.fs.existsSync(t),i=!s&&this.fs.existsSync(e);if(!s&&!i)return{};{const i=s?t:e;try{return JSON.parse(this.fs.readFileSync(i))}catch(t){return{}}}}}writedata(){if(this.isNode()){this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(this.dataFile),e=this.path.resolve(process.cwd(),this.dataFile),s=this.fs.existsSync(t),i=!s&&this.fs.existsSync(e),r=JSON.stringify(this.data);s?this.fs.writeFileSync(t,r):i?this.fs.writeFileSync(e,r):this.fs.writeFileSync(t,r)}}lodash_get(t,e,s){const i=e.replace(/\[(\d+)\]/g,".$1").split(".");let r=t;for(const t of i)if(r=Object(r)[t],void 0===r)return s;return r}lodash_set(t,e,s){return Object(t)!==t?t:(Array.isArray(e)||(e=e.toString().match(/[^.[\]]+/g)||[]),e.slice(0,-1).reduce((t,s,i)=>Object(t[s])===t[s]?t[s]:t[s]=Math.abs(e[i+1])>>0==+e[i+1]?[]:{},t)[e[e.length-1]]=s,t)}getdata(t){let e=this.getval(t);if(/^@/.test(t)){const[,s,i]=/^@(.*?)\.(.*?)$/.exec(t),r=s?this.getval(s):"";if(r)try{const t=JSON.parse(r);e=t?this.lodash_get(t,i,""):e}catch(t){e=""}}return e}setdata(t,e){let s=!1;if(/^@/.test(e)){const[,i,r]=/^@(.*?)\.(.*?)$/.exec(e),o=this.getval(i),h=i?"null"===o?null:o||"{}":"{}";try{const e=JSON.parse(h);this.lodash_set(e,r,t),s=this.setval(JSON.stringify(e),i)}catch(e){const o={};this.lodash_set(o,r,t),s=this.setval(JSON.stringify(o),i)}}else s=this.setval(t,e);return s}getval(t){return this.isSurge()||this.isLoon()?$persistentStore.read(t):this.isQuanX()?$prefs.valueForKey(t):this.isNode()?(this.data=this.loaddata(),this.data[t]):this.data&&this.data[t]||null}setval(t,e){return this.isSurge()||this.isLoon()?$persistentStore.write(t,e):this.isQuanX()?$prefs.setValueForKey(t,e):this.isNode()?(this.data=this.loaddata(),this.data[e]=t,this.writedata(),!0):this.data&&this.data[e]||null}initGotEnv(t){this.got=this.got?this.got:require("got"),this.cktough=this.cktough?this.cktough:require("tough-cookie"),this.ckjar=this.ckjar?this.ckjar:new this.cktough.CookieJar,t&&(t.headers=t.headers?t.headers:{},void 0===t.headers.Cookie&&void 0===t.cookieJar&&(t.cookieJar=this.ckjar))}get(t,e=(()=>{})){t.headers&&(delete t.headers["Content-Type"],delete t.headers["Content-Length"]),this.isSurge()||this.isLoon()?(this.isSurge()&&this.isNeedRewrite&&(t.headers=t.headers||{},Object.assign(t.headers,{"X-Surge-Skip-Scripting":!1})),$httpClient.get(t,(t,s,i)=>{!t&&s&&(s.body=i,s.statusCode=s.status),e(t,s,i)})):this.isQuanX()?(this.isNeedRewrite&&(t.opts=t.opts||{},Object.assign(t.opts,{hints:!1})),$task.fetch(t).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>e(t))):this.isNode()&&(this.initGotEnv(t),this.got(t).on("redirect",(t,e)=>{try{if(t.headers["set-cookie"]){const s=t.headers["set-cookie"].map(this.cktough.Cookie.parse).toString();this.ckjar.setCookieSync(s,null),e.cookieJar=this.ckjar}}catch(t){this.logErr(t)}}).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>{const{message:s,response:i}=t;e(s,i,i&&i.body)}))}post(t,e=(()=>{})){if(t.body&&t.headers&&!t.headers["Content-Type"]&&(t.headers["Content-Type"]="application/x-www-form-urlencoded"),t.headers&&delete t.headers["Content-Length"],this.isSurge()||this.isLoon())this.isSurge()&&this.isNeedRewrite&&(t.headers=t.headers||{},Object.assign(t.headers,{"X-Surge-Skip-Scripting":!1})),$httpClient.post(t,(t,s,i)=>{!t&&s&&(s.body=i,s.statusCode=s.status),e(t,s,i)});else if(this.isQuanX())t.method="POST",this.isNeedRewrite&&(t.opts=t.opts||{},Object.assign(t.opts,{hints:!1})),$task.fetch(t).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>e(t));else if(this.isNode()){this.initGotEnv(t);const{url:s,...i}=t;this.got.post(s,i).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>{const{message:s,response:i}=t;e(s,i,i&&i.body)})}}time(t){let e={"M+":(new Date).getMonth()+1,"d+":(new Date).getDate(),"H+":(new Date).getHours(),"m+":(new Date).getMinutes(),"s+":(new Date).getSeconds(),"q+":Math.floor(((new Date).getMonth()+3)/3),S:(new Date).getMilliseconds()};/(y+)/.test(t)&&(t=t.replace(RegExp.$1,((new Date).getFullYear()+"").substr(4-RegExp.$1.length)));for(let s in e)new RegExp("("+s+")").test(t)&&(t=t.replace(RegExp.$1,1==RegExp.$1.length?e[s]:("00"+e[s]).substr((""+e[s]).length)));return t}msg(e=t,s="",i="",r){const o=t=>{if(!t)return t;if("string"==typeof t)return this.isLoon()?t:this.isQuanX()?{"open-url":t}:this.isSurge()?{url:t}:void 0;if("object"==typeof t){if(this.isLoon()){let e=t.openUrl||t.url||t["open-url"],s=t.mediaUrl||t["media-url"];return{openUrl:e,mediaUrl:s}}if(this.isQuanX()){let e=t["open-url"]||t.url||t.openUrl,s=t["media-url"]||t.mediaUrl;return{"open-url":e,"media-url":s}}if(this.isSurge()){let e=t.url||t.openUrl||t["open-url"];return{url:e}}}};this.isMute||(this.isSurge()||this.isLoon()?$notification.post(e,s,i,o(r)):this.isQuanX()&&$notify(e,s,i,o(r)));let h=["","==============\ud83d\udce3\u7cfb\u7edf\u901a\u77e5\ud83d\udce3=============="];h.push(e),s&&h.push(s),i&&h.push(i),console.log(h.join("\n")),this.logs=this.logs.concat(h)}log(...t){t.length>0&&(this.logs=[...this.logs,...t]),console.log(t.join(this.logSeparator))}logErr(t,e){const s=!this.isSurge()&&!this.isQuanX()&&!this.isLoon();s?this.log("",`\u2757\ufe0f${this.name}, \u9519\u8bef!`,t.stack):this.log("",`\u2757\ufe0f${this.name}, \u9519\u8bef!`,t)}wait(t){return new Promise(e=>setTimeout(e,t))}done(t={}){const e=(new Date).getTime(),s=(e-this.startTime)/1e3;this.log("",`\ud83d\udd14${this.name}, \u7ed3\u675f! \ud83d\udd5b ${s} \u79d2`),this.log(),(this.isSurge()||this.isQuanX()||this.isLoon())&&$done(t)}}(t,e)} \ No newline at end of file +function Env(t,e){class s{constructor(t){this.env=t}send(t,e="GET"){t="string"==typeof t?{url:t}:t;let s=this.get;return"POST"===e&&(s=this.post),new Promise((e,i)=>{s.call(this,t,(t,s,r)=>{t?i(t):e(s)})})}get(t){return this.send.call(this.env,t)}post(t){return this.send.call(this.env,t,"POST")}}return new class{constructor(t,e){this.name=t,this.http=new s(this),this.data=null,this.dataFile="box.dat",this.logs=[],this.isMute=!1,this.isNeedRewrite=!1,this.logSeparator="\n",this.startTime=(new Date).getTime(),Object.assign(this,e),this.log("",`\ud83d\udd14${this.name}, \u5f00\u59cb!`)}isNode(){return"undefined"!=typeof module&&!!module.exports}isQuanX(){return"undefined"!=typeof $task}isSurge(){return"undefined"!=typeof $httpClient&&"undefined"==typeof $loon}isLoon(){return"undefined"!=typeof $loon}toObj(t,e=null){try{return JSON.parse(t)}catch{return e}}toStr(t,e=null){try{return JSON.stringify(t)}catch{return e}}getjson(t,e){let s=e;const i=this.getdata(t);if(i)try{s=JSON.parse(this.getdata(t))}catch{}return s}setjson(t,e){try{return this.setdata(JSON.stringify(t),e)}catch{return!1}}getScript(t){return new Promise(e=>{this.get({url:t},(t,s,i)=>e(i))})}runScript(t,e){return new Promise(s=>{let i=this.getdata("@chavy_boxjs_userCfgs.httpapi");i=i?i.replace(/\n/g,"").trim():i;let r=this.getdata("@chavy_boxjs_userCfgs.httpapi_timeout");r=r?1*r:20,r=e&&e.timeout?e.timeout:r;const[o,h]=i.split("@"),a={url:`http://${h}/v1/scripting/evaluate`,body:{script_text:t,mock_type:"cron",timeout:r},headers:{"X-Key":o,Accept:"*/*"}};this.post(a,(t,e,i)=>s(i))}).catch(t=>this.logErr(t))}loaddata(){if(!this.isNode())return{};{this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(this.dataFile),e=this.path.resolve(process.cwd(),this.dataFile),s=this.fs.existsSync(t),i=!s&&this.fs.existsSync(e);if(!s&&!i)return{};{const i=s?t:e;try{return JSON.parse(this.fs.readFileSync(i))}catch(t){return{}}}}}writedata(){if(this.isNode()){this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(this.dataFile),e=this.path.resolve(process.cwd(),this.dataFile),s=this.fs.existsSync(t),i=!s&&this.fs.existsSync(e),r=JSON.stringify(this.data);s?this.fs.writeFileSync(t,r):i?this.fs.writeFileSync(e,r):this.fs.writeFileSync(t,r)}}lodash_get(t,e,s){const i=e.replace(/\[(\d+)\]/g,".$1").split(".");let r=t;for(const t of i)if(r=Object(r)[t],void 0===r)return s;return r}lodash_set(t,e,s){return Object(t)!==t?t:(Array.isArray(e)||(e=e.toString().match(/[^.[\]]+/g)||[]),e.slice(0,-1).reduce((t,s,i)=>Object(t[s])===t[s]?t[s]:t[s]=Math.abs(e[i+1])>>0==+e[i+1]?[]:{},t)[e[e.length-1]]=s,t)}getdata(t){let e=this.getval(t);if(/^@/.test(t)){const[,s,i]=/^@(.*?)\.(.*?)$/.exec(t),r=s?this.getval(s):"";if(r)try{const t=JSON.parse(r);e=t?this.lodash_get(t,i,""):e}catch(t){e=""}}return e}setdata(t,e){let s=!1;if(/^@/.test(e)){const[,i,r]=/^@(.*?)\.(.*?)$/.exec(e),o=this.getval(i),h=i?"null"===o?null:o||"{}":"{}";try{const e=JSON.parse(h);this.lodash_set(e,r,t),s=this.setval(JSON.stringify(e),i)}catch(e){const o={};this.lodash_set(o,r,t),s=this.setval(JSON.stringify(o),i)}}else s=this.setval(t,e);return s}getval(t){return this.isSurge()||this.isLoon()?$persistentStore.read(t):this.isQuanX()?$prefs.valueForKey(t):this.isNode()?(this.data=this.loaddata(),this.data[t]):this.data&&this.data[t]||null}setval(t,e){return this.isSurge()||this.isLoon()?$persistentStore.write(t,e):this.isQuanX()?$prefs.setValueForKey(t,e):this.isNode()?(this.data=this.loaddata(),this.data[e]=t,this.writedata(),!0):this.data&&this.data[e]||null}initGotEnv(t){this.got=this.got?this.got:require("got"),this.cktough=this.cktough?this.cktough:require("tough-cookie"),this.ckjar=this.ckjar?this.ckjar:new this.cktough.CookieJar,t&&(t.headers=t.headers?t.headers:{},void 0===t.headers.Cookie&&void 0===t.cookieJar&&(t.cookieJar=this.ckjar))}get(t,e=(()=>{})){t.headers&&(delete t.headers["Content-Type"],delete t.headers["Content-Length"]),this.isSurge()||this.isLoon()?(this.isSurge()&&this.isNeedRewrite&&(t.headers=t.headers||{},Object.assign(t.headers,{"X-Surge-Skip-Scripting":!1})),$httpClient.get(t,(t,s,i)=>{!t&&s&&(s.body=i,s.statusCode=s.status),e(t,s,i)})):this.isQuanX()?(this.isNeedRewrite&&(t.opts=t.opts||{},Object.assign(t.opts,{hints:!1})),$task.fetch(t).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>e(t))):this.isNode()&&(this.initGotEnv(t),this.got(t).on("redirect",(t,e)=>{try{if(t.headers["set-cookie"]){const s=t.headers["set-cookie"].map(this.cktough.Cookie.parse).toString();this.ckjar.setCookieSync(s,null),e.cookieJar=this.ckjar}}catch(t){this.logErr(t)}}).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>{const{message:s,response:i}=t;e(s,i,i&&i.body)}))}post(t,e=(()=>{})){if(t.body&&t.headers&&!t.headers["Content-Type"]&&(t.headers["Content-Type"]="application/x-www-form-urlencoded"),t.headers&&delete t.headers["Content-Length"],this.isSurge()||this.isLoon())this.isSurge()&&this.isNeedRewrite&&(t.headers=t.headers||{},Object.assign(t.headers,{"X-Surge-Skip-Scripting":!1})),$httpClient.post(t,(t,s,i)=>{!t&&s&&(s.body=i,s.statusCode=s.status),e(t,s,i)});else if(this.isQuanX())t.method="POST",this.isNeedRewrite&&(t.opts=t.opts||{},Object.assign(t.opts,{hints:!1})),$task.fetch(t).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>e(t));else if(this.isNode()){this.initGotEnv(t);const{url:s,...i}=t;this.got.post(s,i).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>{const{message:s,response:i}=t;e(s,i,i&&i.body)})}}time(t){let e={"M+":(new Date).getMonth()+1,"d+":(new Date).getDate(),"H+":(new Date).getHours(),"m+":(new Date).getMinutes(),"s+":(new Date).getSeconds(),"q+":Math.floor(((new Date).getMonth()+3)/3),S:(new Date).getMilliseconds()};/(y+)/.test(t)&&(t=t.replace(RegExp.$1,((new Date).getFullYear()+"").substr(4-RegExp.$1.length)));for(let s in e)new RegExp("("+s+")").test(t)&&(t=t.replace(RegExp.$1,1==RegExp.$1.length?e[s]:("00"+e[s]).substr((""+e[s]).length)));return t}msg(e=t,s="",i="",r){const o=t=>{if(!t)return t;if("string"==typeof t)return this.isLoon()?t:this.isQuanX()?{"open-url":t}:this.isSurge()?{url:t}:void 0;if("object"==typeof t){if(this.isLoon()){let e=t.openUrl||t.url||t["open-url"],s=t.mediaUrl||t["media-url"];return{openUrl:e,mediaUrl:s}}if(this.isQuanX()){let e=t["open-url"]||t.url||t.openUrl,s=t["media-url"]||t.mediaUrl;return{"open-url":e,"media-url":s}}if(this.isSurge()){let e=t.url||t.openUrl||t["open-url"];return{url:e}}}};this.isMute||(this.isSurge()||this.isLoon()?$notification.post(e,s,i,o(r)):this.isQuanX()&&$notify(e,s,i,o(r)));let h=["","==============\ud83d\udce3\u7cfb\u7edf\u901a\u77e5\ud83d\udce3=============="];h.push(e),s&&h.push(s),i&&h.push(i),console.log(h.join("\n")),this.logs=this.logs.concat(h)}log(...t){t.length>0&&(this.logs=[...this.logs,...t]),console.log(t.join(this.logSeparator))}logErr(t,e){const s=!this.isSurge()&&!this.isQuanX()&&!this.isLoon();s?this.log("",`\u2757\ufe0f${this.name}, \u9519\u8bef!`,t.stack):this.log("",`\u2757\ufe0f${this.name}, \u9519\u8bef!`,t)}wait(t){return new Promise(e=>setTimeout(e,t))}done(t={}){const e=(new Date).getTime(),s=(e-this.startTime)/1e3;this.log("",`\ud83d\udd14${this.name}, \u7ed3\u675f! \ud83d\udd5b ${s} \u79d2`),this.log(),(this.isSurge()||this.isQuanX()||this.isLoon())&&$done(t)}}(t,e)} diff --git a/TaskConf/README.md b/TaskConf/README.md new file mode 100644 index 0000000000..62ac3b2ed3 --- /dev/null +++ b/TaskConf/README.md @@ -0,0 +1,72 @@ +# 目录导航 + +本目录为快捷直达所需配置地址页,点击蓝色字体即可 +相关配置还在完善中,敬请等待 + +> [回到主页](https://github.com/Sunert/Scripts) + +### 一、本仓库重写配置集 + * Surge + * [Cookie](https://raw.githubusercontent.com/Sunert/Profiles/master/Surge/Modules/Sunert_Cookie.sgmodule) + * [任务模块](https://raw.githubusercontent.com/Sunert/Profiles/master/Surge/Modules/Sunert_Task.sgmodule) +

+ * Loon + * [Cookie](https://raw.githubusercontent.com/Sunert/Profiles/master/Loon/Sunet_Cookie.plugin) + * [任务插件](https://raw.githubusercontent.com/Sunert/Profiles/master/Loon/Sunert_Task.plugin) +

+ * Quantumult X + * [Cookie](https://raw.githubusercontent.com/Sunert/Profiles/master/QuantumultX/Rewrite/Sunert_Cookie.conf) + * [任务仓库](https://raw.githubusercontent.com/Sunert/Scripts/master/Task/Sunert_Task.json) + +### 二、[Boxjs订阅](https://raw.githubusercontent.com/Sunert/Scripts/master/Task/sunert.boxjs.json) + + ``` +https://raw.githubusercontent.com/Sunert/Scripts/master/Task/sunert.boxjs.json + ``` + +### 三、任务配置目录 + + * 中青看点 + * [任务配置](https://github.com/Sunert/Scripts/tree/master/TaskConf/youth) + * [脚本地址](https://raw.githubusercontent.com/Sunert/Scripts/master/Task/youth.js) +

+ * 腾讯新闻 + * [任务配置](https://github.com/Sunert/Scripts/tree/master/TaskConf/txnews) + * [脚本地址](https://raw.githubusercontent.com/Sunert/Scripts/master/Task/txnews.js) +

+ * 百度极速 + * [任务配置](https://github.com/Sunert/Scripts/tree/master/TaskConf/baidu) + * [脚本地址](https://raw.githubusercontent.com/Sunert/Scripts/master/Task/baidu_speed.js) +

+ * 聚看点 + * [任务配置](https://github.com/Sunert/Scripts/tree/master/TaskConf/jukan) + * [脚本地址](https://raw.githubusercontent.com/Sunert/Scripts/master/Task/jukan.js) +

+ * 电视家 + * [任务配置](https://github.com/Sunert/Scripts/tree/master/TaskConf/dianshijia) + * [脚本地址](https://raw.githubusercontent.com/Sunert/Scripts/master/Task/dianshijia.js) +

+ * 电信套餐查询 + * [任务配置](https://github.com/Sunert/Scripts/tree/master/TaskConf/dianxin) + * [脚本地址](https://raw.githubusercontent.com/Sunert/Scripts/master/Task/telecomInfinity.js) +

+ * 快手视频签到 + * [任务配置](https://github.com/Sunert/Scripts/tree/master/TaskConf/kuaishou) + * [脚本地址](https://raw.githubusercontent.com/Sunert/Scripts/master/Task/kuaishou.js) +

+ * 数码之家 + * [任务配置](https://github.com/Sunert/Scripts/tree/master/TaskConf/digital_home) + * [脚本地址](https://raw.githubusercontent.com/Sunert/Scripts/master/Task/mydigit.js) +

+ * 京东系 + * [任务配置](https://github.com/Sunert/Scripts/tree/master/TaskConf/jd) + * 脚本地址 + * [京东到家](https://raw.githubusercontent.com/Sunert/Scripts/master/Task/jddk.js) + * [来客有礼](https://raw.githubusercontent.com/Sunert/Scripts/master/Task/lkyl.js) +

+ * 新浪系 + * [任务配置](https://github.com/Sunert/Scripts/tree/master/TaskConf/sina) + * 脚本地址 + * [微博](https://raw.githubusercontent.com/Sunert/Scripts/master/Task/weibo.js) + * [新浪新闻](https://raw.githubusercontent.com/Sunert/Scripts/master/Task/sinanews.js) + diff --git a/TaskConf/dianshijia/loon.plugin b/TaskConf/dianshijia/loon.plugin new file mode 100644 index 0000000000..c57c3fff5c --- /dev/null +++ b/TaskConf/dianshijia/loon.plugin @@ -0,0 +1,8 @@ +# 电视家重写配置 + +[Script] +cron "1 7,12,20 * * *" script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/dianshijia.js, tag=电视家 + +http-request http:\/\/api\.gaoqingdianshi\.com\/api\/v\d\/sign\/signin script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/dianshijia.js, timeout=10, tag=电视家 + +http-request http:\/\/api\.gaoqingdianshi\.com\/api\/v2\/cash\/withdrawal script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/dianshijia.js, timeout=10, tag=电视家 \ No newline at end of file diff --git a/TaskConf/dianshijia/qx_rewite.txt b/TaskConf/dianshijia/qx_rewite.txt new file mode 100644 index 0000000000..dbc3699e5f --- /dev/null +++ b/TaskConf/dianshijia/qx_rewite.txt @@ -0,0 +1,4 @@ +# hostname = +http:\/\/api\.gaoqingdianshi\.com\/api\/v\d\/sign\/signin url script-request-header https://raw.githubusercontent.com/Sunert/Scripts/master/Task/dianshijia.js + +http:\/\/api\.gaoqingdianshi\.com\/api\/v2\/cash\/withdrawal url script-request-header https://raw.githubusercontent.com/Sunert/Scripts/master/Task/dianshijia.js diff --git a/TaskConf/dianshijia/readme.md b/TaskConf/dianshijia/readme.md new file mode 100644 index 0000000000..741f85c444 --- /dev/null +++ b/TaskConf/dianshijia/readme.md @@ -0,0 +1,114 @@ + + + [toc] + + #
电视家使用说明
+ + [跳转至底部](#注意事项) ---- [回到主页](https://github.com/Sunert/Scripts) + +### IOS配置教程 + +#### Surge: +* [模块地址](https://raw.githubusercontent.com/Sunert/Scripts/master/TaskConf/dianshijia/surge.sgmodule) + + ``` +https://raw.githubusercontent.com/Sunert/Scripts/master/TaskConf/dianshijia/surge.sgmodule + ``` + * 本地重写 + + ``` +[Script] + +电视家 = type=cron,cronexp=1 7,12,20 * * *,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/dianshijia.js,script-update-interval=0 + +电视家 = type=http-request,pattern=http:\/\/api\.gaoqingdianshi\.com\/api\/v\d\/sign\/signin,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/dianshijia.js + +电视家 = type=http-request,pattern=http:\/\/api\.gaoqingdianshi\.com\/api\/v2\/cash\/withdrawal,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/dianshijia.js +``` +#### Shadowrocket(Cron配置): + +``` +[Script] +电视家 = type=cron,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/dianshijia.js,cronexpr="1 7,12,20 * * *",timeout=20,enable=true +``` +#### Loon: + +* [插件地址](https://raw.githubusercontent.com/Sunert/Scripts/master/TaskConf/dianshijia/loon.plugin) + + ``` +https://raw.githubusercontent.com/Sunert/Scripts/master/TaskConf/dianshijia/loon.plugin + ``` +* 本地重写 + + ``` +[Script] +cron "1 7,12,20 * * *" script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/dianshijia.js, tag=电视家 + +http-request http:\/\/api\.gaoqingdianshi\.com\/api\/v\d\/sign\/signin script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/dianshijia.js, timeout=10, tag=电视家 + +http-request http:\/\/api\.gaoqingdianshi\.com\/api\/v2\/cash\/withdrawal script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/dianshijia.js, timeout=10, tag=电视家 +``` +#### Quantumult X: + * [远程重写配置](https://raw.githubusercontent.com/Sunert/Scripts/master/TaskConf/dianshijia/qx_rewite.txt) + +``` +[rewrite_remote] +https://raw.githubusercontent.com/Sunert/Scripts/master/TaskConf/dianshijia/qx_rewite.txt +``` + * 本地重写配置 + +``` +[rewrite_local] +http:\/\/api\.gaoqingdianshi\.com\/api\/v\d\/sign\/signin url script-request-header https://raw.githubusercontent.com/Sunert/Scripts/master/Task/dianshijia.js + +http:\/\/api\.gaoqingdianshi\.com\/api\/v2\/cash\/withdrawal url script-request-header https://raw.githubusercontent.com/Sunert/Scripts/master/Task/dianshijia.js +``` + * 本地任务配置 + +``` +[task_local] +1 7,12,20 * * * https://raw.githubusercontent.com/Sunert/Scripts/master/Task/dianshijia.js +``` +### 获取Cookie方法 + +赞赏:电视家邀请码`893988`,农妇山泉 -> 有点咸,万分感谢 + + 1. APP登陆账号后,点击菜单栏'领现金',即可获取Cookie + 2. 进入提现页面,点击随机金额,可获取提现地址!! + 3. 无需添加 hostname,每日7点、12点、20点各运行一次,其他随意 + + + >>> [回到顶部](#IOS配置教程) + +### Nodejs 配置密钥 (Github Actions) + +
+ + + + Actions Secrets + + + +| Name | 脚本相关YML | Value分割符 | 必须 / 可选 | 注意事项及样式(其中"xxx"代表任意字符) | +| :-------: | :------: | :-------: | ------ | ------- | +| DSJ_HEADERS | 电视家dianshijia.yml | #或换行 | 必须 | 请求地址: "http://api.gaoqingdianshi.com/api/v2/sign/signin",
签到请求头: { xxx } | +| DSJ_DRAWAL | 同上 | #或换行 | 必须 | 请求地址: "http://api.gaoqingdianshi.com/api/v2/cash/withdrawal",
即提现请求地址 | +| DSJ_NOTIFY_CONTROL | 同上 | true/false | 可选 | 电视家通知开关
默认不推送 | + +
+ + >>> [回到上一页](..) + +### 注意事项: + > + + + + + + + + + + diff --git a/TaskConf/dianshijia/surge.sgmodule b/TaskConf/dianshijia/surge.sgmodule new file mode 100644 index 0000000000..4855b4125e --- /dev/null +++ b/TaskConf/dianshijia/surge.sgmodule @@ -0,0 +1,10 @@ +#!name= dianshijia Rewrite +#!desc= 电视家重写配置 +#!system=ios + +[Script] +电视家 = type=cron,cronexp=1 7,12,20 * * *,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/dianshijia.js,script-update-interval=0 + +电视家 = type=http-request,pattern=http:\/\/api\.gaoqingdianshi\.com\/api\/v\d\/sign\/signin,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/dianshijia.js + +电视家 = type=http-request,pattern=http:\/\/api\.gaoqingdianshi\.com\/api\/v2\/cash\/withdrawal,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/dianshijia.js \ No newline at end of file diff --git a/TaskConf/dianxin/qx_rewite.txt b/TaskConf/dianxin/qx_rewite.txt new file mode 100644 index 0000000000..f2c3ae11b4 --- /dev/null +++ b/TaskConf/dianxin/qx_rewite.txt @@ -0,0 +1,3 @@ +hostname = e.189.cn + +^https?:\/\/e\.189\.cn\/store\/user\/package_detail\.do url script-request-header https://raw.githubusercontent.com/Sunert/Scripts/master/Task/telecomInfinity.js diff --git a/TaskConf/dianxin/readme.md b/TaskConf/dianxin/readme.md new file mode 100644 index 0000000000..7dfe66e4d8 --- /dev/null +++ b/TaskConf/dianxin/readme.md @@ -0,0 +1,33 @@ +更新时间: 2020-10-12 20:05 + 1.根据原版脚本修改,增加上月账单信息,需重新获取Cookie,打开app即可 + 2.适合流量畅享套餐使用,其他套餐,自行测试,此项仅供测试 + 3.可能因地区不同,脚本不一定适用 + By Macsuny 修改 + 感谢原版作者提供脚本 + * 下载安装 天翼账号中心 登陆 获取authToken + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# quantumultx + [rewrite_local] + ^https?:\/\/e\.189\.cn\/store\/user\/package_detail\.do url script-request-header telecomInfinity.js + # MITM = e.189.cn + [task_local] + 10 8 * * * telecomInfinity.js + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# [Loon] +cron "04 00 * * *" script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/telecomInfinity.js, enabled=true, tag=电信套餐查询 + +http-request ^https?:\/\/e\.189\.cn\/store\/user\/package_detail\.do script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/telecomInfinity.js + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +# Surge 4.0 : +[Script] +电信套餐查询 = type=cron,cronexp=35 5 0 * * *,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/telecomInfinity.js,script-update-interval=0 + +电信套餐查询 = script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/telecomInfinity.js,type=http-request,pattern=https?:\/\/e\.189\.cn\/store\/user\/package_detail\.do + +~~~~~~~~~~~~~~~~~~~~~ + # MITM +hostname = e.189.cn diff --git a/TaskConf/digital_home/qx_rewite.txt b/TaskConf/digital_home/qx_rewite.txt new file mode 100644 index 0000000000..b9ddddba80 --- /dev/null +++ b/TaskConf/digital_home/qx_rewite.txt @@ -0,0 +1,3 @@ +hostname = www.mydigit.cn + +https:\/\/www\.mydigit\.cn\/plugin\.php\?id=k_misign:sign&operation=qiandao url script-request-header https://raw.githubusercontent.com/Sunert/Scripts/master/Task/mydigit.js diff --git a/TaskConf/digital_home/readme.md b/TaskConf/digital_home/readme.md new file mode 100644 index 0000000000..d425f4740a --- /dev/null +++ b/TaskConf/digital_home/readme.md @@ -0,0 +1,34 @@ +本脚本仅适用于数码之家每日签到 +获取Cookie方法: +1.将下方[rewrite_local]和[MITM]地址复制的相应的区域 +下, + +2.登陆数码之家电脑版网页,签到一次,即可获取Cookie,获取后请禁用或注释掉❗️ 签过到的需次日获取 + +3.非专业人士制作,欢迎各位大佬提出宝贵意见和指导 + +by Macsuny +~~~~~~~~~~~~~~~~ +Surge 4.0 : +[Script] +数码之家 = type=cron,cronexp=35 5 0 * * *,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/mydigit.js,script-update-interval=0 + +# 数码之家 Cookie. +数码之家 = type=http-request,pattern=https:\/\/www\.mydigit\.cn\/plugin\.php\?id=k_misign:sign&operation=qiandao,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/mydigit.js +~~~~~~~~~~~~~~~~ +Loon 2.1.0+ +[Script] +cron "04 00 * * *" script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/mydigit.js, enabled=true, tag=数码之家 + +http-request https:\/\/www\.mydigit\.cn\/plugin\.php\?id=k_misign:sign&operation=qiandao script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/mydigit.js +----------------- + +QX 1.0. 7+ : +[task_local] +0 9 * * * https://raw.githubusercontent.com/Sunert/Scripts/master/Task/mydigit.js + +[rewrite_local] +https:\/\/www\.mydigit\.cn\/plugin\.php\?id=k_misign:sign&operation=qiandao url script-request-header https://raw.githubusercontent.com/Sunert/Scripts/master/Task/mydigit.js +~~~~~~~~~~~~~~~~ +[MITM] +hostname = www.mydigit.cn diff --git a/TaskConf/jd/qx_rewite.txt b/TaskConf/jd/qx_rewite.txt new file mode 100644 index 0000000000..ffbc4116a1 --- /dev/null +++ b/TaskConf/jd/qx_rewite.txt @@ -0,0 +1,9 @@ +# 增加lxk0301大佬多ck脚本 + +hostname = daojia.jd.com, draw.jdfcloud.com, wq.jd.com + +https:\/\/daojia\.jd\.com\/client\?_jdrandom=\d{13}&functionId=%2Fsignin url script-request-header https://raw.githubusercontent.com/Sunert/Scripts/master/Task/jddj.js + +https:\/\/draw\.jdfcloud\.com\/\/api\/bean\/square\/silverBean\/task\/get\? url script-request-header https://raw.githubusercontent.com/Sunert/Scripts/master/Task/lkyl.js + +https:\/\/wq\.jd\.com\/user_new\/info\/GetJDUserInfoUnion url script-request-header https://gitee.com/lxk0301/jd_scripts/raw/master/JD_extra_cookie.js diff --git a/TaskConf/jd/readme.md b/TaskConf/jd/readme.md new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/TaskConf/jd/readme.md @@ -0,0 +1 @@ + diff --git a/TaskConf/jukan/qx_rewite.txt b/TaskConf/jukan/qx_rewite.txt new file mode 100644 index 0000000000..5005af2bc1 --- /dev/null +++ b/TaskConf/jukan/qx_rewite.txt @@ -0,0 +1,3 @@ +hostname = www.xiaodouzhuan.cn + +https:\/\/www\.xiaodouzhuan\.cn\/jkd\/newMobileMenu\/infoMe\.action url script-request-body https://raw.githubusercontent.com/Sunert/Scripts/master/Task/jukan.js diff --git a/TaskConf/jukan/readme.md b/TaskConf/jukan/readme.md new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/TaskConf/jukan/readme.md @@ -0,0 +1 @@ + diff --git a/TaskConf/kuaishou/loon.plugin b/TaskConf/kuaishou/loon.plugin new file mode 100644 index 0000000000..d7290d1bbc --- /dev/null +++ b/TaskConf/kuaishou/loon.plugin @@ -0,0 +1,10 @@ + +[Script] +cron "4 0 * * *" script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/kuaishou.js, enabled=true, tag=快手视频 + +http-request https:\/\/activity\.m\.kuaishou\.com\/rest\/wd\/taskCenter\/\w+\/module\/list script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/kuaishou.js, enabled=true, tag=快手视频正式版 + +http-request https:\/\/nebula\.kuaishou\.com\/nebula\/task\/earning\? script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/kuaishou.js, enabled=true, tag=快手视频极速版 + +[MITM] +hostname = nebula.kuaishou.com, activity.m.kuaishou.com \ No newline at end of file diff --git a/TaskConf/kuaishou/qx_rewite.txt b/TaskConf/kuaishou/qx_rewite.txt new file mode 100644 index 0000000000..5a4198bc11 --- /dev/null +++ b/TaskConf/kuaishou/qx_rewite.txt @@ -0,0 +1,5 @@ +hostname = nebula.kuaishou.com, activity.m.kuaishou.com + +https:\/\/activity\.m\.kuaishou\.com\/rest\/wd\/taskCenter\/\w+\/module\/list url script-request-header https://raw.githubusercontent.com/Sunert/Scripts/master/Task/kuaishou.js + +https:\/\/nebula\.kuaishou\.com\/nebula\/task\/earning\? url script-request-header https://raw.githubusercontent.com/Sunert/Scripts/master/Task/kuaishou.js diff --git a/TaskConf/kuaishou/readme.md b/TaskConf/kuaishou/readme.md new file mode 100644 index 0000000000..6b674ff14e --- /dev/null +++ b/TaskConf/kuaishou/readme.md @@ -0,0 +1,107 @@ + + + [toc] + + #
快手视频签到使用说明
+ + [跳转至底部](#注意事项) ---- [回到主页](https://github.com/Sunert/Scripts) + +### IOS配置教程 + ``` +[MITM] +hostname = nebula.kuaishou.com, activity.m.kuaishou.com + ``` +#### Surge: +* [模块地址](https://raw.githubusercontent.com/Sunert/Scripts/master/TaskConf/kuaishou/surge.sgmodule) + + ``` +https://raw.githubusercontent.com/Sunert/Scripts/master/TaskConf/kuaishou/surge.sgmodule + ``` + * 本地重写 + + ``` +[Script] +快手视频 = type=cron,cronexp=35 5 0 * * *,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/kuaishou.js,script-update-interval=0 + +# 获取快手视频 Cookie. +快手正式版 = type=http-request,pattern=https:\/\/activity\.m\.kuaishou\.com\/rest\/wd\/taskCenter\/\w+\/module\/list,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/kuaishou.js +快手极速版 = type=http-request,pattern=https:\/\/nebula\.kuaishou\.com\/nebula\/task\/earning\?,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/kuaishou.js +``` +#### Shadowrocket(Cron配置): + +``` +[Script] +快手视频 = type=cron,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/kuaishou.js,cronexpr="35 5 0 * * *",timeout=20,enable=true +``` +#### Loon: + +* [插件地址](https://raw.githubusercontent.com/Sunert/Scripts/master/TaskConf/kuaishou/loon.plugin) + + ``` +https://raw.githubusercontent.com/Sunert/Scripts/master/TaskConf/kuaishou/loon.plugin + ``` +* 本地重写 + + ``` +[Script] +cron "4 0 * * *" script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/kuaishou.js, enabled=true, tag=快手视频 + +http-request https:\/\/activity\.m\.kuaishou\.com\/rest\/wd\/taskCenter\/\w+\/module\/list script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/kuaishou.js, enabled=true, tag=快手视频正式版 +http-request https:\/\/nebula\.kuaishou\.com\/nebula\/task\/earning\? script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/kuaishou.js, enabled=true, tag=快手视频极速版 +``` +#### Quantumult X: + * [远程重写配置](https://raw.githubusercontent.com/Sunert/Scripts/master/TaskConf/kuaishou/qx_rewite.txt) + +``` +[rewrite_remote] +https://raw.githubusercontent.com/Sunert/Scripts/master/TaskConf/kuaishou/qx_rewite.txt +``` + * 本地重写配置 + +``` +[rewrite_local] +https:\/\/activity\.m\.kuaishou\.com\/rest\/wd\/taskCenter\/\w+\/module\/list url script-request-header https://raw.githubusercontent.com/Sunert/Scripts/master/Task/kuaishou.js +https:\/\/nebula\.kuaishou\.com\/nebula\/task\/earning\? url script-request-header https://raw.githubusercontent.com/Sunert/Scripts/master/Task/kuaishou.js +``` + * 本地任务配置 + +``` +[task_local] +1 0 * * * https://raw.githubusercontent.com/Sunert/Scripts/master/Task/kuaishou.js, tag=快手视频 +``` +### 获取Cookie方法 + 1. 点击视频页悬浮红包,或者进入设置,点击"积分兑好礼"即可 + + >>> [回到顶部](#IOS配置教程) + +### Nodejs 配置密钥 (Github Actions) + +
+ + + + Actions Secrets + + + +| Name | 脚本相关YML | Value分割符 | 必须 / 可选 | 注意事项及样式(其中"xxx"代表任意字符) | +| :-------: | :------: | :-------: | ------ | ------- | +| KS_TOKEN | 快手视频 | &或换行 | 必须 | 请求地址: "https://activity.m.kuaishou.com/rest/wd/taskCenter/lowActive/module/list",
任务Cookie: uid=xxx&gsid=xxx&s=xxx | + +
+ + >>> [回到上一页](..) + +### 注意事项: + * 本脚本仅限快手视频"低活国庆"部分任务,不能自动刷视频,可以自动领取视频积分 + * 本脚本仅适用于快手双版本签到,仅支持正式版获取多Cookie,建议使用正式版获取Cookie + + + + + + + + + + diff --git a/TaskConf/kuaishou/surge.sgmodule b/TaskConf/kuaishou/surge.sgmodule new file mode 100644 index 0000000000..8e58c395a7 --- /dev/null +++ b/TaskConf/kuaishou/surge.sgmodule @@ -0,0 +1,13 @@ + +#!name= kuaishou Rewrite +#!desc= 快手重写配置 +#!system=ios + +[Script] +快手视频 = type=cron,cronexp=35 5 0 * * *,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/kuaishou.js,script-update-interval=0 + +快手正式版 = type=http-request,pattern=https:\/\/activity\.m\.kuaishou\.com\/rest\/wd\/taskCenter\/\w+\/module\/list,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/kuaishou.js +快手极速版 = type=http-request,pattern=https:\/\/nebula\.kuaishou\.com\/nebula\/task\/earning\?,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/kuaishou.js + +[MITM] +hostname = %APPEND% nebula.kuaishou.com, activity.m.kuaishou.com \ No newline at end of file diff --git a/TaskConf/sina/loon.plugin b/TaskConf/sina/loon.plugin new file mode 100644 index 0000000000..d12291382e --- /dev/null +++ b/TaskConf/sina/loon.plugin @@ -0,0 +1,12 @@ +# 仅新浪微博配置,不包含新浪新闻 + +[Script] +cron "4 0 * * *" script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/weibo.js, enabled=true, tag=新浪微博 + +http-request https:\/\/api\.weibo\.cn\/\d\/users\/show script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/weibo.js, enabled=true, tag=新浪微博 + +http-request https:\/\/m\.weibo\.cn\/c\/checkin\/ug\/v2\/signin\/module\?module script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/weibo.js, enabled=true, tag=新浪微博 + + +[MITM] +hostname = api.weibo.cn, m.weibo.cn \ No newline at end of file diff --git a/TaskConf/sina/qx_rewite.txt b/TaskConf/sina/qx_rewite.txt new file mode 100644 index 0000000000..764fab18ec --- /dev/null +++ b/TaskConf/sina/qx_rewite.txt @@ -0,0 +1,15 @@ +hostname = newsapi.sina.cn, api.weibo.cn, lite.sina.cn, m.weibo.cn + +https:\/\/newsapi\.sina\.cn\/\?resource=hbpage&newsId=HB-1-sina_gold_center url script-request-header https://raw.githubusercontent.com/Sunert/Scripts/master/Task/sinanews.js + +https:\/\/newsapi\.sina\.cn\/\?resource=userpoint\/signIn url script-request-header https://raw.githubusercontent.com/Sunert/Scripts/master/Task/sinanews.js + +https:\/\/api\.weibo\.cn\/\d\/users\/show url script-request-header https://raw.githubusercontent.com/Sunert/Scripts/master/Task/weibo.js + +https:\/\/m\.weibo\.cn\/c\/checkin\/ug\/v2\/signin\/module\?module url script-request-header https://raw.githubusercontent.com/Sunert/Scripts/master/Task/weibo.js + +https?:\/\/lite\.sina\.cn\/\?resource=hbpage&newsId=HB-1-sina_gold_center - script-request-header https://raw.githubusercontent.com/Sunert/Scripts/master/Task/sinanews.js + +https?:\/\/lite\.sina\.cn\/\?resource=userpoint\/signIn - script-request-header https://raw.githubusercontent.com/Sunert/Scripts/master/Task/sinanews.js + + diff --git a/TaskConf/sina/readme.md b/TaskConf/sina/readme.md new file mode 100644 index 0000000000..6150806a7c --- /dev/null +++ b/TaskConf/sina/readme.md @@ -0,0 +1,106 @@ + + [toc] + + #
新浪微博使用说明
+ + [跳转至底部](#注意事项) ---- [回到主页](https://github.com/Sunert/Scripts) + +### IOS配置教程 + ``` +[MITM] +hostname = api.weibo.cn, m.weibo.cn + ``` +#### Surge: +* [模块地址](https://raw.githubusercontent.com/Sunert/Scripts/master/TaskConf/sina/surge.sgmodule) + + ``` +https://raw.githubusercontent.com/Sunert/Scripts/master/TaskConf/sina/surge.sgmodule + ``` + * 本地重写 + + ``` +[Script] +微博&钱包签到 = type=cron,cronexp=35 5 0 * * *,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/weibo.js,script-update-interval=0 + +# 获取微博 Cookie. +微博签到 = type=http-request,pattern=https:\/\/api\.weibo\.cn\/\d\/users\/show,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/weibo.js +微博签到 = type=http-request,pattern=https:\/\/m\.weibo\.cn\/c\/checkin\/ug\/v2\/signin\/module\?module,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/weibo.js +``` +#### Shadowrocket(Cron配置): + +``` +[Script] +新浪微博 = type=cron,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/weibo.js,cronexpr="35 5 0 * * *",timeout=20,enable=true +``` +#### Loon: + +* [插件地址](https://raw.githubusercontent.com/Sunert/Scripts/master/TaskConf/sina/loon.plugin) + + ``` +https://raw.githubusercontent.com/Sunert/Scripts/master/TaskConf/sina/loon.plugin + ``` +* 本地重写 + + ``` +[Script] +cron "4 0 * * *" script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/weibo.js, enabled=true, tag=新浪微博 + +http-request https:\/\/api\.weibo\.cn\/\d\/users\/show script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/weibo.js, enabled=true, tag=新浪微博 +http-request https:\/\/m\.weibo\.cn\/c\/checkin\/ug\/v2\/signin\/module\?module script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/weibo.js, enabled=true, tag=新浪微博 +``` +#### Quantumult X: + * [远程重写配置](https://raw.githubusercontent.com/Sunert/Scripts/master/TaskConf/sina/qx_rewite.txt) + +``` +[rewrite_remote] +https://raw.githubusercontent.com/Sunert/Scripts/master/TaskConf/sina/qx_rewite.txt +``` + * 本地重写配置 + +``` +[rewrite_local] +https:\/\/api\.weibo\.cn\/\d\/users\/show url script-request-header https://raw.githubusercontent.com/Sunert/Scripts/master/Task/weibo.js +https:\/\/m\.weibo\.cn\/c\/checkin\/ug\/v2\/signin\/module\?module url script-request-header https://raw.githubusercontent.com/Sunert/Scripts/master/Task/weibo.js +``` + * 本地任务配置 + +``` +[task_local] +1 0 * * * https://raw.githubusercontent.com/Sunert/Scripts/master/Task/weibo.js, tag=新浪微博 +``` +### 获取Cookie方法 + 1. 打开微博App,获取Cookie,获取后请注释或禁用Cookie + 2. 进入"用户任务中心",获取用户信息Cookie(可选,增加显示个人任务红包余额) + + >>> [回到顶部](#IOS配置教程) + +### Nodejs 配置密钥 (Github Actions) + +
+ + + + Actions Secrets + + + +| Name | 脚本相关YML | Value分割符 | 必须 / 可选 | 注意事项及样式(其中"xxx"代表任意字符) | +| :-------: | :------: | :-------: | ------ | ------- | +| WB_TOKEN | 微博 | #或换行 | 必须 | 请求地址: "https://api.weibo.cn/2/users/show",
签到token: uid=xxx&gsid=xxx&s=xxx | + +
+ + >>> [回到上一页](..) + +### 注意事项: + + + + + + + + + + + diff --git a/TaskConf/sina/surge.sgmodule b/TaskConf/sina/surge.sgmodule new file mode 100644 index 0000000000..1828e419d2 --- /dev/null +++ b/TaskConf/sina/surge.sgmodule @@ -0,0 +1,14 @@ +#!name= weibo Rewrite +#!desc= 新浪微博重写配置 +#!system=ios + +[Script] +微博&钱包签到 = type=cron,cronexp=35 5 0 * * *,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/weibo.js,script-update-interval=0 + +# 获取微博 Cookie. +微博签到 = type=http-request,pattern=https:\/\/api\.weibo\.cn\/\d\/users\/show,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/weibo.js + +微博签到 = type=http-request,pattern=https:\/\/m\.weibo\.cn\/c\/checkin\/ug\/v2\/signin\/module\?module,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/weibo.js + +[MITM] +hostname = %APPEND% api.weibo.cn, m.weibo.cn \ No newline at end of file diff --git a/TaskConf/txnews/loon.plugin b/TaskConf/txnews/loon.plugin new file mode 100644 index 0000000000..4d89c3cb5d --- /dev/null +++ b/TaskConf/txnews/loon.plugin @@ -0,0 +1,8 @@ +[Script] + +cron ”04 00 * * *“ script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/txnews.js, enabled=true, tag=腾讯新闻 + +http-request https:\/\/api\.inews\.qq\.com\/event\/v1\/user\/event\/report\? script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/txnews.js, requires-body=true, enabled=true, tag=腾讯新闻 + +[MITM] +hostname = api.inews.qq.com \ No newline at end of file diff --git a/TaskConf/txnews/qx_rewite.txt b/TaskConf/txnews/qx_rewite.txt new file mode 100644 index 0000000000..b51e880152 --- /dev/null +++ b/TaskConf/txnews/qx_rewite.txt @@ -0,0 +1,3 @@ +hostname = api.inews.qq.com + +https:\/\/api\.inews\.qq\.com\/event\/v1\/user\/event\/report\? url script-request-body https://raw.githubusercontent.com/Sunert/Scripts/master/Task/txnews.js diff --git a/TaskConf/txnews/readme.md b/TaskConf/txnews/readme.md new file mode 100644 index 0000000000..edd10e9b71 --- /dev/null +++ b/TaskConf/txnews/readme.md @@ -0,0 +1,109 @@ + + + [toc] + + #
腾讯新闻使用说明
+ + [跳转至底部](#注意事项) ---- [回到主页](https://github.com/Sunert/Scripts) + +### IOS配置教程 + ``` +[MITM] +hostname = api.inews.qq.com + ``` +#### Surge: +* [模块地址](https://raw.githubusercontent.com/Sunert/Scripts/master/TaskConf/txnews/surge.sgmodule) + + ``` +https://raw.githubusercontent.com/Sunert/Scripts/master/TaskConf/txnews/surge.sgmodule + ``` + * 本地重写 + + ``` +[Script] +腾讯新闻 = type=cron,cronexp=0 8 0 * * *,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/txnews.js,script-update-interval=0 + +腾讯新闻 = type=http-request,pattern=https:\/\/api\.inews\.qq\.com\/event\/v1\/user\/event\/report\?,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/txnews.js, requires-body=true +``` +#### Shadowrocket(Cron配置): + +``` +[Script] +腾讯新闻 = type=cron,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/txnews.js,cronexpr="1 */6 * * *",timeout=20,enable=true +``` +#### Loon: + +* [插件地址](https://raw.githubusercontent.com/Sunert/Scripts/master/TaskConf/txnews/loon.plugin) + + ``` +https://raw.githubusercontent.com/Sunert/Scripts/master/TaskConf/txnews/loon.plugin + ``` +* 本地重写 + + ``` +[Script] +cron "04 00 * * *" script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/txnews.js, enabled=true, tag=腾讯新闻 +http-request https:\/\/api\.inews\.qq\.com\/event\/v1\/user\/event\/report\? script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/txnews.js, requires-body=true, enabled=true, tag=腾讯新闻 +``` +#### Quantumult X: + * [远程重写配置](https://raw.githubusercontent.com/Sunert/Scripts/master/TaskConf/txnews/qx_rewite.txt) + +``` +[rewrite_remote] +https://raw.githubusercontent.com/Sunert/Scripts/master/TaskConf/txnews/qx_rewite.txt +``` + * 本地重写配置 + +``` +[rewrite_local] +https:\/\/api\.inews\.qq\.com\/event\/v1\/user\/event\/report\? url script-request-body https://raw.githubusercontent.com/Sunert/Scripts/master/Task/txnews.js +``` + * 本地任务配置 + +``` +[task_local] +1 */5 * * * https://raw.githubusercontent.com/Sunert/Scripts/master/Task/txnews.js, tag=腾讯新闻 +``` +### 获取Cookie方法 + + 1. 打开腾讯新闻app,阅读几篇文章,倒计时结束后即可获取阅读Cookie + + 2. 看一次推荐视频,获取视频地址 + + >>> [回到顶部](#IOS配置教程) + +### Nodejs 配置密钥 (Github Actions) + +
+ + + + Actions Secrets + + + +| Name | 脚本相关YML | Value分割符 | 必须 / 可选 | 注意事项及样式(其中"xxx"代表任意字符) | +| :-------: | :------: | :-------: | ------ | ------- | +| TXNEWS_COOKIE | 腾讯新闻 txnews.yml | & | 必须 | 请求地址: "https://api.inews.qq.com/event/v1/user/event/report?",
腾讯新闻 Cookie: openxx=xxx | +| TXNEWS_SIGN | 同上 | # | 必须 | 请求地址同上, 阅读请求地址链接 | +| TXNEWS_VIDEO | 同上 | # | 必须 | 请求地址同上, 视频请求地址链接 | +| TXNEWS_NOTIFY_CONTROL | 同上 | true/false | 可选 | 腾讯新闻通知开关
默认当余额大于2元且通知间隔为50时推送通知 | + +
+ + >>> [回到上一页](..) + +### 注意事项: + 1. 可能腾讯有某些限制,有些号码无法领取红包,手动阅读几篇,能领取红包,一般情况下都是正常的 + 2. 此脚本根据阅读篇数开启通知,默认阅读50篇通知一次 + 3. 支持boxjs配置,增加通知跳转链接https://news.qq.com/FERD/cjRedDown.htm,需手动领取此红包 + + + + + + + + + + diff --git a/TaskConf/txnews/surge.sgmodule b/TaskConf/txnews/surge.sgmodule new file mode 100644 index 0000000000..20ad01b199 --- /dev/null +++ b/TaskConf/txnews/surge.sgmodule @@ -0,0 +1,11 @@ +#!name= txnews Rewrite +#!desc= 腾讯新闻重写配置 +#!system=ios + +[Script] +腾讯新闻 = type=cron,cronexp=0 8 0 * * *,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/txnews.js,script-update-interval=0 + +腾讯新闻 = type=http-request,pattern=https:\/\/api\.inews\.qq\.com\/event\/v1\/user\/event\/report\?,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/txnews.js, requires-body=true + +[MITM] +hostname = api.inews.qq.com \ No newline at end of file diff --git a/TaskConf/youth/loon.plugin b/TaskConf/youth/loon.plugin new file mode 100644 index 0000000000..04984ad990 --- /dev/null +++ b/TaskConf/youth/loon.plugin @@ -0,0 +1,11 @@ +# 中青看点获取Cookie + +[Script] +cron "04 00 * * *" script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/youth.js, enabled=true, tag=中青看点 +http-request https:\/\/kd\.youth\.cn\/WebApi\/NewTaskIos\/getTaskList script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/youth.js, enabled=true, tag=中青看点 +http-request https:\/\/ios\.baertt\.com\/v5\/article\/info\/get\.json script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/youth.js, enabled=true, tag=中青看点 +http-request https:\/\/ios\.baertt\.com\/v5\/user\/stay\.json script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/youth.js, requires-body=true, enabled=true, tag=中青看点 +http-request https:\/\/ios\.baertt\.com\/v5\/\w+\/withdraw\d?\.json script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/youth.js, requires-body=true, enabled=true, tag=中青看点 + +[MITM] +hostname = ios.baertt.com, kd.youth.cn \ No newline at end of file diff --git a/TaskConf/youth/qx_rewite.txt b/TaskConf/youth/qx_rewite.txt new file mode 100644 index 0000000000..1606f9642b --- /dev/null +++ b/TaskConf/youth/qx_rewite.txt @@ -0,0 +1,11 @@ +hostname = kd.youth.cn, ios.baertt.com + +https:\/\/kd\.youth\.cn\/WebApi\/NewTaskIos\/getTaskList url script-request-header https://raw.githubusercontent.com/Sunert/Scripts/master/Task/youth.js + +https:\/\/ios\.baertt\.com\/v5\/article\/info\/get\.json url script-request-header https://raw.githubusercontent.com/Sunert/Scripts/master/Task/youth.js + +https:\/\/ios\.baertt\.com\/v5\/user\/stay\.json url script-request-body https://raw.githubusercontent.com/Sunert/Scripts/master/Task/youth.js + +https:\/\/ios\.baertt\.com\/v5\/task\/browse_(start|end)\.json url script-request-body https://raw.githubusercontent.com/Sunert/Scripts/master/Task/youth_gain.js + +https:\/\/ios\.baertt\.com\/v5\/\w+\/withdraw\d?\.json url script-request-body https://raw.githubusercontent.com/Sunert/Scripts/master/Task/youth.js diff --git a/TaskConf/youth/qx_youthread.txt b/TaskConf/youth/qx_youthread.txt new file mode 100644 index 0000000000..ebafb1cc4c --- /dev/null +++ b/TaskConf/youth/qx_youthread.txt @@ -0,0 +1,5 @@ +hostname = ios.baertt.com + +https:\/\/ios\.baertt\.com\/v5\/article\/info\/get\.json url script-request-header https://raw.githubusercontent.com/Sunert/Scripts/master/Task/Youth_Read.js + +https:\/\/ios\.baertt\.com\/v5\/user\/stay\.json url script-request-body https://raw.githubusercontent.com/Sunert/Scripts/master/Task/Youth_Read.js \ No newline at end of file diff --git a/TaskConf/youth/readme.md b/TaskConf/youth/readme.md new file mode 100644 index 0000000000..5355e390aa --- /dev/null +++ b/TaskConf/youth/readme.md @@ -0,0 +1,120 @@ + + + [toc] + + #
中青看点使用说明
+ + [跳转至底部](#注意事项) ---- [回到主页](https://github.com/Sunert/Scripts) + +### IOS配置教程 + ``` +[MITM] +hostname = kd.youth.cn, ios.baertt.com + ``` +#### Surge: +* [模块地址](https://raw.githubusercontent.com/Sunert/Scripts/master/TaskConf/youth/surge.sgmodule) + + ``` +https://raw.githubusercontent.com/Sunert/Scripts/master/TaskConf/youth/surge.sgmodule + ``` + * 本地重写 + + ``` +[Script] +中青看点 = type=cron,cronexp=35 5 0 * * *,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/youth.js,script-update-interval=0 +中青看点 = type=http-request,pattern=https:\/\/kd\.youth\.cn\/WebApi\/NewTaskIos\/getTaskList,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/youth.js +中青看点 = type=http-request,pattern=https:\/\/ios\.baertt\.com\/v5\/article\/info\/get\.json,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/youth.js, requires-body=true +中青看点 = type=http-request,pattern=https:\/\/ios\.baertt\.com\/v5\/user\/stay\.json,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/youth.js, requires-body=true +中青看点 = type=http-request,pattern=https:\/\/ios\.baertt\.com\/v5\/\w+\/withdraw\d?\.json,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/youth.js, requires-body=true +``` +#### Shadowrocket(Cron配置): + +``` +[Script] +中青看点 = type=cron,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/youth.js,cronexpr="1 */6 * * *",timeout=20,enable=true +``` +#### Loon: + +* [插件地址](https://raw.githubusercontent.com/Sunert/Scripts/master/TaskConf/youth/loon.plugin) + + ``` +https://raw.githubusercontent.com/Sunert/Scripts/master/TaskConf/youth/loon.plugin + ``` +* 本地重写 + + ``` +[Script] +cron "04 00 * * *" script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/youth.js, enabled=true, tag=中青看点 +http-request https:\/\/kd\.youth\.cn\/WebApi\/NewTaskIos\/getTaskList script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/youth.js, enabled=true, tag=中青看点 +http-request https:\/\/ios\.baertt\.com\/v5\/article\/info\/get\.json script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/youth.js, requires-body=true, enabled=true, tag=中青看点 +http-request https:\/\/ios\.baertt\.com\/v5\/user\/stay\.json script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/youth.js, requires-body=true, enabled=true, tag=中青看点 +http-request https:\/\/ios\.baertt\.com\/v5\/\w+\/withdraw\d?\.json script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/youth.js, requires-body=true, enabled=true, tag=中青看点 +``` +#### Quantumult X: + * [远程重写配置](https://raw.githubusercontent.com/Sunert/Scripts/master/TaskConf/youth/qx_rewite.txt) + +``` +[rewrite_remote] +https://raw.githubusercontent.com/Sunert/Scripts/master/TaskConf/youth/qx_rewite.txt +``` + * 本地重写配置 + +``` +[rewrite_local] +https:\/\/kd\.youth\.cn\/WebApi\/NewTaskIos\/getTaskList url script-request-header https://raw.githubusercontent.com/Sunert/Scripts/master/Task/youth.js +https:\/\/ios\.baertt\.com\/v5\/article\/info\/get\.json url script-request-header https://raw.githubusercontent.com/Sunert/Scripts/master/Task/youth.js +https:\/\/ios\.baertt\.com\/v5\/user\/stay\.json url script-request-body https://raw.githubusercontent.com/Sunert/Scripts/master/Task/youth.js +https:\/\/ios\.baertt\.com\/v5\/\w+\/withdraw\d?\.json url script-request-body https://raw.githubusercontent.com/Sunert/Scripts/master/Task/youth.js +``` + * 本地任务配置 + +``` +[task_local] +1 */5 * * * https://raw.githubusercontent.com/Sunert/Scripts/master/Task/youth.js, enabled=true, tag=中青看点 +``` +### 获取Cookie方法 + * 打开极速版APP,进去我的"任务中心",提示获取Cookie + - 打开一篇短文资讯,提示获取阅读请求 + * 多阅读几篇短文,随机获取阅读时长请求(至少1分钟左右,增加时长有关) + - 正常提现一次,获取提现请求(可选,AC无添加) + + >>> [回到顶部](#IOS配置教程) + +### Nodejs 配置密钥 (Github Actions) + +
+ + + + Actions Secrets + + + +| Name | 脚本相关YML | Value分割符 | 必须 / 可选 | 注意事项及样式(其中"xxx"代表任意字符) | +| :-------: | :------: | :-------: | ------ | ------- | +| YOUTH_HEADER | 中青看点 youth.yml | #或者换行 | 必须 | 请求地址: "https://kd.youth.cn/WebApi/NewTaskIos/getTaskList",
中青签到请求头引用: uid=xxx&cookie_id=xxx&cookie=xxx | +| YOUTH_ARTBODY | 同上 | &或者换行 | 必须 | 请求地址: "https://ios.baertt.com/v5/article/complete",
阅读请求体: p=xxx | +| YOUTH_TIME | 同上 | &或者换行 | 必须 | 请求地址: "https://ios.baertt.com/v5/user/stay.json",
阅读时长请求体: p=xxx | +| YOUTH_NOTIFY_CONTROL | 同上 | true/false | 可选 | 中青通知开关
默认当转盘次数为50或者100并且余额大于10元时推送通知 | +| | | | - | | +| YOUTH_READ | 中青阅读 youth_read.yml | &或者换行 | 必须 | 请求地址: "https://ios.baertt.com/v5/article/complete",
阅读请求体: p=xxx | +| YOUTH_START | 中青浏览赚 youth_gain.yml | & | 必须 | 请求地址: "https://ios.baertt.com/v5/task/browse_start.json",
阅读请求体: p=xxx | +| YOUTH_END | 同上 | & | 必须 | 请求地址: "https://ios.baertt.com/v5/task/browse_end.json",
阅读请求体: p=xxx | + +
+ + >>> [回到上一页](..) + +### 注意事项: + - __提现金额需该请求一致,只更改提现金额无效,默认30元__ + + * __惊喜红包已下架,现所有请求均采用IOS新版APP任务__ + + + + + + + + + diff --git a/TaskConf/youth/surge.sgmodule b/TaskConf/youth/surge.sgmodule new file mode 100644 index 0000000000..69edfa174c --- /dev/null +++ b/TaskConf/youth/surge.sgmodule @@ -0,0 +1,17 @@ +#!name= Youth Rewrite +#!desc= 中青极速版重写配置 +#!system=ios + +[Script] +中青看点 = type=cron,cronexp=35 5 0 * * *,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/youth.js,script-update-interval=0 + +中青看点 = type=http-request,pattern=https:\/\/kd\.youth\.cn\/WebApi\/NewTaskIos\/getTaskList,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/youth.js + +中青看点 = type=http-request,pattern=https:\/\/ios\.baertt\.com\/v5\/article\/info\/get\.json,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/youth.js + +中青看点 = type=http-request,pattern=https:\/\/ios\.baertt\.com\/v5\/user\/stay\.json,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/youth.js, requires-body=true + +中青看点 = type=http-request,pattern=https:\/\/ios\.baertt\.com\/v5\/\w+\/withdraw\d?\.json,script-path=https://raw.githubusercontent.com/Sunert/Scripts/master/Task/youth.js, requires-body=true + +[MITM] +hostname = %APPEND% kd.youth.cn, ios.baertt.com \ No newline at end of file diff --git a/package.json b/package.json index e8a427d084..e764e0f9d5 100644 --- a/package.json +++ b/package.json @@ -8,10 +8,10 @@ }, "repository": { "type": "git", - "url": "git+https://github.com/Sunert/Scripts.git" + "url": "https://github.com/Sunert/Scripts.git" }, - "keywords": [], - "author": "", + "keywords": ["中青看点,腾讯新闻等等"], + "author": "Sunert", "license": "ISC", "bugs": { "url": "https://github.com/Sunert/Scripts/issues" @@ -19,12 +19,9 @@ "homepage": "https://github.com/Sunert/Scripts#readme", "dependencies": { "crypto-js": "^4.0.0", - "got": "^11.5.1", + "got": "^11.7.0", "http-server": "^0.12.3", - "node-schedule": "^1.3.2", "tough-cookie": "^4.0.0", - "download": "^8.0.0", - "request": "^2.88.2", - "request-promise": "^4.2.5" + "download": "^8.0.0" } } diff --git a/weather.js b/weather.js deleted file mode 100644 index 9a36346219..0000000000 --- a/weather.js +++ /dev/null @@ -1,30 +0,0 @@ -var appid="47273245"; -var appsecret="BCK1QTW5"; - -var wurl = { - url: "https://www.tianqiapi.com/api/?version=v6&appid=" + appid + "&appsecret=" + appsecret, -}; - -$task.fetch(wurl).then(response => { - var obj = JSON.parse(response.body); - var city = obj.city; - var noweather = obj.wea; - var wind_dir = obj.win; - var wind_sc = obj.win_speed; - var hum = obj.humidity; - var lowtmp = obj.tem2; - var hightmp = obj.tem1; - var air = obj.air_pm25; - var airlevel =obj.air_level; - var airtips = obj.air_tips; - var updatetime = obj.date + " " + obj.update_time; - - var title = city + "天气: "+ noweather +", " + "气温: " + lowtmp +" °C " + "~" + hightmp +" °C " - var mation = "风向: " + wind_dir + "·" + wind_sc + " | " + "湿度: " + hum + " | " + "PM2.5: " + air + " " + airlevel - var tips = "建议: " + airtips - var update = "更新于: " + updatetime - $notify(title, mation, tips, update); - -}, reason => { - $notify("错误", "", reason.error); -}); \ No newline at end of file diff --git a/weather_pro.js b/weather_pro.js deleted file mode 100644 index cd777aaaee..0000000000 --- a/weather_pro.js +++ /dev/null @@ -1,847 +0,0 @@ -/* -可以自由定制显示的天气脚本,想怎样都随你,轻松修改轻松查看 -https://github.com/sazs34/TaskConfig/blob/master/assets/weather_pro.md - */ -let config = { - darksky_api: "", //从https://darksky.net/dev/ 上申请key填入即可 - aqicn_api: "", //从http://aqicn.org/data-platform/token/#/ 上申请key填入即可 - huweather_apiKey: "", //和风天气APIkey,可自行前往 https://dev.heweather.com/ 进行获取 - lat_lon: "", //请填写经纬度,直接从谷歌地图中获取即可 - lang: "zh", //语言,随意切换为您想要的语言哦(zh/zh-tw/ja/en/fr/...) - log: 0, //调试日志,0为不开启,1为开启,2为开启精简日志 - timeout: 0, //超时时间,单位毫秒(1000毫秒=1秒),一般不推荐修改[为0则不限制超时时间] - show: { - //普通每天的 - template: { - title: `$[city]$[district] $[summary]`, - subtitle: `$[weatherIcon]$[weather] $[temperatureMin] ~ $[temperatureMax]°C ☔️降雨概率 $[precipProbability]%`, - detail: `$[aqiIcon]空气质量 $[aqi]($[aqiDesc]) 🏋🏻‍♀️气压$[atmosphere]pa -🌪风速$[windSpeed]km/h 💨$[windDir]$[windPower]级 -👀紫外线指数 $[uv]($[uvDesc]) 💦湿度$[currentHumidity]% -🌡体感温度 $[apparentTemperatureMin] ~ $[apparentTemperatureMax]°C 🎚当前温度 $[currentTemperature]℃ -[生活指数] -$[lifeStyle($[icon]:$[brf],$[txt])] -[天气周报] $[weeklySummary] -$[daily($[month]月$[day]日 $[temperatureLow]~$[temperatureHigh]°C $[weatherIcon]$[weather])]` - }, - lifestyle: { //此处用于显示各项生活指数,可自行调整顺序,顺序越在前面则显示也会靠前,如果您不想查看某一指数,置为false即可,想看置为true即可 - drsg: true, //穿衣指数, - flu: true, //感冒指数, - comf: true, //舒适度指数, - cw: false, //洗车指数, - sport: false, //运动指数, - trav: false, //旅游指数, - uv: false, //紫外线指数, - air: true, //空气污染扩散条件指数, - ac: false, //空调开启指数, - ag: false, //过敏指数, - gl: false, //太阳镜指数, - mu: false, //化妆指数, - airc: false, //晾晒指数, - ptfc: true, //交通指数, - fsh: false, //钓鱼指数, - spi: false, //防晒指数 - } - } -} - -const provider = { - heweather_now: { - api: `https://free-api.heweather.net/s6/weather/now?location=${config.lat_lon.replace(/\s/g, "").replace(",", ",")}&key=${config.huweather_apiKey}`, - progress: 0, //处理进度:0需处理1已处理2无需处理9报错 - timeoutNumber: 0, //超时处理编号 - data: { - basic: {}, - now: {} - }, - support: ['$[province]', '$[city]', '$[district]', '$[weatherIcon]', '$[weather]', '$[currentTemperature]', '$[currentWindSpeed]', '$[currentWindDir]', '$[currentWindPower]', '$[currentHumidity]', '$[currentAtmosphere]', '$[currentVisibility]'] - }, - heweather_daily: { - api: `https://free-api.heweather.net/s6/weather/forecast?location=${config.lat_lon.replace(/\s/g, "").replace(",", ",")}&key=${config.huweather_apiKey}`, - progress: 0, - timeoutNumber: 0, - data: {}, - support: ['$[temperatureMin]', '$[temperatureMax]', '$[precipProbability]', '$[windSpeed]', '$[windDir]', '$[windPower]', '$[humidity]', '$[atmosphere]', '$[visibility]', '$[uv]', '$[uvDesc]', '$[sunrise]', '$[sunset]', '$[moonrise]', '$[moonset]'] - }, - heweather_air: { - api: `https://free-api.heweather.net/s6/air/now?location=auto_ip&key=${config.huweather_apiKey}`, - progress: 0, - timeoutNumber: 0, - data: {}, - support: [] - }, - heweather_lifestyle: { - api: `https://free-api.heweather.net/s6/weather/lifestyle?location=${config.lat_lon.replace(/\s/g, "").replace(",", ",")}&key=${config.huweather_apiKey}`, - progress: 0, - timeoutNumber: 0, - data: [], - support: ['$[lifeStyle]'] - }, - darksky: { - api: `https://api.darksky.net/forecast/${config.darksky_api}/${config.lat_lon.replace(/\s/g, "").replace(",", ",")}?lang=${config.lang}&units=si`, - progress: 0, - timeoutNumber: 0, - data: { - daily: { - data: [] - }, - hourly: { - data: [] - }, - currently: {} - }, - support: ['$[summary]', '$[weeklySummary]', '$[weatherIcon]', '$[weather]', '$[temperatureMin]', '$[temperatureMax]', '$[apparentTemperatureMin]', '$[apparentTemperatureMax]', '$[precipProbability]', '$[uv]', '$[uvDesc]'] - }, - aqicn: { - api: `https://api.waqi.info/feed/geo:${config.lat_lon.replace(/\s/g, "").replace(",", ",").replace(/,/, ";")}/?token=${config.aqicn_api}`, - progress: 0, - data: {}, - support: ['$[aqiIcon]', '$[aqi]', '$[aqiDesc]', '$[aqiWarning]'] - } -} -// #region 天气数据获取 -function weather() { - support(); - heweatherNow(); - heweatherDaily(); - darksky(); - aqicn(); - heweatherLifestyle(); -} -//clear-day, partly-cloudy-day, cloudy, clear-night, rain, snow, sleet, wind, fog, or partly-cloudy-night -//☀️🌤⛅️🌥☁️🌦🌧⛈🌩🌨❄️💧💦🌫☔️☂️ ☃️⛄️ -function darksky() { - if (provider.darksky.progress == 2) return; - start("darksky"); - $task.fetch({ - url: provider.darksky.api - }).then(response => { - try { - let darkObj = JSON.parse(response.body); - record(`天气数据获取-A1-${response.body}`); - if (darkObj.error) { - $notify("DarkApi", "出错啦", darkObj.error); - } - provider.darksky.data.daily = darkObj.daily; - provider.darksky.data.hourly = darkObj.hourly; - provider.darksky.data.currently = darkObj.currently; - record(`天气数据获取-A2`); - check('darksky', true) - } catch (e) { - console.log(`天气数据A获取报错${JSON.stringify(e)}`) - } - }, reason => { - record(`天气数据获取-A3-${reason.error}`); - check('darksky', false); - }); -} - -function aqicn() { - if (provider.aqicn.progress == 2) return; - start("aqicn"); - $task.fetch({ - url: provider.aqicn.api - }).then(response => { - try { - var waqiObj = JSON.parse(response.body); - if (waqiObj.status == 'error') { - $notify("Aqicn", "出错啦", waqiObj.data); - } else { - record(`天气数据获取-B1-${response.body}`); - provider.aqicn.data = { - ...getAqiInfo(waqiObj.data.aqi) - }; - } - check('aqicn', true) - } catch (e) { - console.log(`天气数据B获取报错${JSON.stringify(e)}`) - } - }, reason => { - record(`天气数据获取-B2-${reason.error}`); - //获取精确数据失败后,直接获取粗略信息即可 - heweatherAir(); - }); -} - -function heweatherNow() { - start("heweather_now"); - $task.fetch({ - url: provider.heweather_now.api - }).then(response => { - try { - record(`天气数据获取-C1-${response.body}`); - var heObj = JSON.parse(response.body); - provider.heweather_now.data.basic = heObj.HeWeather6[0].basic; - provider.heweather_now.data.now = heObj.HeWeather6[0].now; - check('heweather_now', true) - } catch (e) { - console.log(`天气数据C获取报错${JSON.stringify(e)}`) - } - }, reason => { - record(`天气数据获取-C2-${reason.error}`); - //因为此接口出错率还挺高的,所以即使报错我们也不处理,该返回什么就返回什么好了 - check('heweather_now', false) - }) -} - -function heweatherDaily() { - if (provider.heweather_daily.progress == 2) return; - start("heweather_daily"); - $task.fetch({ - url: provider.heweather_daily.api - }).then(response => { - try { - record(`天气数据获取-D1-${response.body}`); - var heObj = JSON.parse(response.body); - provider.heweather_daily.data = heObj.HeWeather6[0].daily_forecast[0]; - check('heweather_daily', true) - } catch (e) { - console.log(`天气数据D获取报错${JSON.stringify(e)}`) - } - }, reason => { - record(`天气数据获取-D2-${reason.error}`); - //因为此接口出错率还挺高的,所以即使报错我们也不处理,该返回什么就返回什么好了 - check('heweather_daily', false) - }) -} - -function heweatherAir() { - if (provider.heweather_air.progress == 2) return; - start("heweather_air"); - $task.fetch({ - url: provider.heweather_air.api - }).then(response => { - try { - record(`天气数据获取F1-${response.body}`); - var heObj = JSON.parse(response.body); - provider.heweather_air.data = { - ...getAqiInfo(heObj.HeWeather6[0].air_now_city.aqi) - }; - check('heweather_air', true) - } catch (e) { - console.log(`天气数据F获取报错${JSON.stringify(e)}`) - } - }, reason => { - record(`天气数据获取-F2-${reason.error}`); - //因为此接口出错率还挺高的,所以即使报错我们也不处理,该返回什么就返回什么好了 - check('heweather_air', false) - }) -} - -function heweatherLifestyle() { - if (provider.heweather_lifestyle.progress == 2) return; - start("heweather_lifestyle"); - var needRequest = false; - //判断一下是否全部都是false,全false的话,则不需要请求此接口直接返回渲染的数据了 - for (var item in config.show.lifestyle) { - if (config.show.lifestyle[item]) { - needRequest = true; - break; - } - } - if (needRequest) { - $task.fetch({ - url: provider.heweather_lifestyle.api - }).then(response => { - try { - record(`天气数据获取-E1-${response.body}`); - var heObj = JSON.parse(response.body); - provider.heweather_lifestyle.data = heObj.HeWeather6[0].lifestyle; - check('heweather_lifestyle', true) - } catch (e) { - console.log(`天气数据E获取报错${JSON.stringify(e)}`) - } - }, reason => { - record(`天气数据获取-E2-${reason.error}`); - //因为此接口出错率还挺高的,所以即使报错我们也不处理,该返回什么就返回什么好了 - check('heweather_lifestyle', false) - }) - } else { - check('heweather_lifestyle', false) - } -} -//#endregion - -// #region 提醒数据组装 -function check(type, result) { - record(`check-${type}-${result}`); - //支持setTimeout居然不支持clearTimeout,有点难受 - if (provider[type].progress == 1 || provider[type].progress == 9) return; - provider[type].progress = result ? 1 : 9; - var isAllChecked = provider.heweather_now.progress != 0 && provider.heweather_daily.progress && provider.darksky.progress != 0 && (provider.aqicn.progress != 0 || provider.heweather_air.progress != 0) && provider.heweather_lifestyle.progress != 0; - if (isAllChecked) { - record(`天气数据渲染中[template]`); - try { - renderTemplate(); - } catch (e) { - record(`天气渲染出错-${JSON.stringify(e)}`); - } - } -} - -var lineBreak = ` -`; - -function renderTemplate() { - execArrayTemplate(); - const map = { - //省 - province: provider.heweather_now.data.basic.admin_area, - //市 - city: provider.heweather_now.data.basic.parent_city, - //区 - district: provider.heweather_now.data.basic.location || "UNKNOW", - //全天气候变化概述 - summary: `${provider.darksky.data.hourly.summary||""}`, - //一周气候变化概述 - weeklySummary: `${provider.darksky.data.daily.summary||""}`, - //天气图标 - weatherIcon: `${getHeweatherIcon(provider.heweather_now.data.now.cond_code)||getDarkskyWeatherIcon(provider.darksky.data.hourly.icon)}`, - //天气描述(晴/雨/雪等) - weather: `${provider.heweather_now.data.now.cond_txt||getDarkskyWeatherDesc(provider.darksky.data.hourly.icon)}`, - //当前温度 - currentTemperature: `${provider.heweather_now.data.now.tmp}`, - //温度最低值 - temperatureMin: `${Math.round(provider.heweather_daily.data.tmp_min||provider.darksky.data.daily.data.get(0).temperatureMin)}`, - //温度最高值 - temperatureMax: `${Math.round(provider.heweather_daily.data.tmp_max||provider.darksky.data.daily.data.get(0).temperatureMax)}`, - //体感温度最低值 - apparentTemperatureMin: `${Math.round(provider.darksky.data.daily.data.get(0).apparentTemperatureLow)}`, - //体感温度最高值 - apparentTemperatureMax: `${Math.round(provider.darksky.data.daily.data.get(0).apparentTemperatureHigh)}`, - //降雨概率 - precipProbability: `${provider.heweather_daily.data.pop||(Number(provider.darksky.data.daily.data.get(0).precipProbability) * 100).toFixed(0)}`, - //空气质量图标 - aqiIcon: `${provider.aqicn.data.aqiIcon||provider.heweather_air.data.aqiIcon}`, - //空气质量 - aqi: `${provider.aqicn.data.aqi||provider.heweather_air.data.aqi}`, - //空气质量描述 - aqiDesc: `${provider.aqicn.data.aqiDesc||provider.heweather_air.data.aqiDesc}`, - //空气质量警告(提示) - aqiWarning: `${provider.aqicn.data.aqiWarning||provider.heweather_air.data.aqiWarning}`, - //全天风速 - windSpeed: `${provider.heweather_daily.data.wind_spd}`, - //当前风速 - currentWindSpeed: `${provider.heweather_now.data.now.wind_spd}`, - //全天风向 - windDir: `${provider.heweather_daily.data.wind_dir}`, - //当前风向 - currentWindDir: `${provider.heweather_now.data.now.wind_dir}`, - //全天风力 - windPower: `${provider.heweather_daily.data.wind_sc}`, - //当前风力 - currentWindPower: `${provider.heweather_now.data.now.wind_sc}`, - //全天相对湿度 - humidity: `${provider.heweather_daily.data.hum}`, - //当前相对湿度 - currentHumidity: `${provider.heweather_now.data.now.hum}`, - //全天大气压 - atmosphere: `${provider.heweather_daily.data.pres}`, - //当前大气压 - currentAtmosphere: `${provider.heweather_now.data.now.pres}`, - //全天能见度 - visibility: `${provider.heweather_daily.data.vis}`, - //当前能见度 - currentVisibility: `${provider.heweather_now.data.now.vis}`, - //紫外线等级 - uv: `${provider.heweather_daily.data.uv_index||provider.darksky.data.daily.data.get(0).uvIndex}`, - //紫外线描述 - uvDesc: `${getUVDesc(provider.heweather_daily.data.uv_index||provider.darksky.data.daily.data.get(0).uvIndex)}`, - //日出时间 - sunrise: `${provider.heweather_daily.data.sr}`, - //日落时间 - sunset: `${provider.heweather_daily.data.ss}`, - //月出时间 - moonrise: `${provider.heweather_daily.data.mr}`, - //月落时间 - moonset: `${provider.heweather_daily.data.ms}`, - } - var notifyInfo = { - title: execTemplate(config.show.template.title, map), - subtitle: execTemplate(config.show.template.subtitle, map), - detail: execTemplate(config.show.template.detail, map), - }; - $notify(notifyInfo.title, notifyInfo.subtitle, notifyInfo.detail); - $done({}); -} -// #endregion - -// #region 数据处理方法 -function getHeweatherIcon(code) { - var codeMap = { - _100: '☀️', - _101: '☁️', - _102: '☁️', - _103: '⛅️', - _104: '☁️', - _200: '💨', - _201: '🌬', - _202: '🌬', - _203: '🌬', - _204: '🌬', - _205: '🌬', - _206: '💨', - _207: '💨', - _208: '💨', - _209: '🌪', - _210: '🌪', - _211: '🌪', - _212: '🌪', - _213: '🌪', - _300: '🌨', - _301: '🌨', - _302: '⛈', - _303: '⛈', - _304: '⛈', - _305: '💧', - _306: '💦', - _307: '🌧', - _308: '🌧', - _309: '☔️', - _310: '🌧', - _311: '🌧', - _312: '🌧', - _313: '🌧❄️', - _314: '💧', - _315: '💦', - _316: '🌧', - _317: '🌧', - _318: '🌧', - _399: '🌧', - _400: '🌨', - _401: '🌨', - _402: '☃️', - _403: '❄️', - _404: '🌨', - _405: '🌨', - _406: '🌨', - _407: '🌨', - _408: '🌨', - _409: '🌨', - _410: '❄️', - _499: '⛄️', - _500: '🌫', - _501: '🌫', - _502: '🌫', - _503: '🌫', - _504: '🌫', - _505: '🌫', - _506: '🌫', - _507: '🌫', - _508: '🌫', - _509: '🌫', - _510: '🌫', - _511: '🌫', - _512: '🌫', - _513: '🌫', - _514: '🌫', - _515: '🌫', - _900: '🔥', - _901: '⛄️', - _999: '❓', - } - return codeMap[`_${code}`] ? codeMap[`_${code}`] : ""; -} - -function getDarkskyWeatherIcon(icon_text) { - let icon = "❓" - if (icon_text == "clear-day") icon = "☀️"; - if (icon_text == "partly-cloudy-day") icon = "🌤"; - if (icon_text == "cloudy") icon = "☁️"; - if (icon_text == "rain") icon = "🌧"; - if (icon_text == "snow") icon = "☃️"; - if (icon_text == "sleet") icon = "🌨"; - if (icon_text == "wind") "🌬"; - if (icon_text == "fog") icon = "🌫"; - if (icon_text == "partly-cloudy-night") icon = "🌑"; - if (icon_text == "clear-night") icon = "🌑"; - return icon; -} - -function getDarkskyWeatherDesc(icon_text) { - let icon = "未知" - if (icon_text == "clear-day") icon = `晴`; - if (icon_text == "partly-cloudy-day") icon = `晴转多云`; - if (icon_text == "cloudy") icon = `多云`; - if (icon_text == "rain") icon = `雨`; - if (icon_text == "snow") icon = `雪`; - if (icon_text == "sleet") icon = `雨夹雪`; - if (icon_text == "wind") icon = `大风`; - if (icon_text == "fog") icon = `大雾`; - if (icon_text == "partly-cloudy-night") icon = `多云`; - if (icon_text == "clear-night") icon = `晴`; - return icon; -} - -function getCityInfo(name) { - var loc; - try { - var locArr = name.split(/[(),,()]/) - if (locArr.length >= 4) { - loc = locArr[2] + " "; - } else if (locArr.length >= 2) { - loc = locArr[1] + " "; - } else { - loc = ""; //此时会很长,还不如不显示了 - } - } catch (e) { - loc = ''; - record(`获取城市名称失败-${JSON.stringify(e)}`); - } - return loc; -} - -function getAqiInfo(aqi) { - var aqiDesc = ""; - var aqiIcon = ""; - var aqiWarning = ""; - if (aqi > 300) { - aqiIcon = `🟤`; - aqiDesc = `严重污染`; - aqiWarning = "儿童、老人、呼吸系统等疾病患者及一般人群停止户外活动"; - } else if (aqi > 200) { - aqiIcon = `🟣`; - aqiDesc = `重度污染`; - aqiWarning = "儿童、老人、呼吸系统等疾病患者及一般人群停止或减少户外运动"; - } else if (aqi > 150) { - aqiIcon = `🔴`; - aqiDesc = `中度污染`; - aqiWarning = "儿童、老人、呼吸系统等疾病患者及一般人群减少户外活动"; - } else if (aqi > 100) { - aqiIcon = `🟠`; - aqiDesc = `轻度污染`; - aqiWarning = "老人、儿童、呼吸系统等疾病患者减少长时间、高强度的户外活动"; - } else if (aqi > 50) { - aqiIcon = `🟡`; - aqiDesc = `良好`; - aqiWarning = "极少数敏感人群应减少户外活动"; - } else { - aqiIcon = `🟢`; - aqiDesc = `优`; - } - return { - aqi, - aqiIcon, - aqiDesc, - aqiWarning - }; -} - -function getUVDesc(daily_uvIndex) { - var uvDesc = ""; - if (daily_uvIndex >= 10) { - uvDesc = "五级-特别强"; - } else if (daily_uvIndex >= 7) { - uvDesc = "四级-很强"; - } else if (daily_uvIndex >= 5) { - uvDesc = "三级-较强"; - } else if (daily_uvIndex >= 3) { - uvDesc = "二级-较弱"; - } else { - uvDesc = "一级-最弱"; - } - return uvDesc; -} -// #endregion - -// #region 模板相关 -/** - * 用于标识该接口已执行,如果有使用超时设置则此操作是有意义的 - * @param {String} type 具体的接口执行类型 - */ -function start(type) { - if (config.timeout > 0) { - provider[type].timeoutNumber = setTimeout(() => { - check(type, false); - }, config.timeout); - } -} -/** - * 判断哪些接口需要进行处理,减少网络请求 - */ -function support() { - let regex = /\$\[([a-z,A-Z,0-9]*)\]/g; - const template = `${config.show.template.title}${config.show.template.subtitle}${config.show.template.detail}`.match(regex); - provider.heweather_now.progress = template.filter((item, filter) => { - return provider.heweather_now.support.indexOf(item) != -1; - }).length > 0 ? 0 : 2; - provider.heweather_daily.progress = template.filter((item, filter) => { - return provider.heweather_daily.support.indexOf(item) != -1; - }).length > 0 ? 0 : 2; - // provider.heweather_air.progress = template.filter((item, filter) => { - // return provider.heweather_air.support.indexOf(item) != -1; - // }).length > 0 ? 0 : 2; - provider.heweather_lifestyle.progress = template.filter((item, filter) => { - let regexLifestyle = /\$\[(lifeStyle\()+([\s\S]+?)(\))+\]/g; - return regexLifestyle.test(config.show.lifestyle) ? 0 : 2; - }).length > 0 ? 0 : 2; - provider.aqicn.progress = template.filter((item, filter) => { - return provider.aqicn.support.indexOf(item) != -1; - }).length > 0 ? 0 : 2; - provider.darksky.progress = template.filter((item, filter) => { - return provider.darksky.support.indexOf(item) != -1; - }).length > 0 ? 0 : 2; - if (provider.darksky.progress == 2) { - //如果 - let regexDaily = /\$\[(daily\()+([\s\S]+?)(\))+\]/g; - let regexHourly = /\$\[(hourly\()+([\s\S]+?)(\))+\]/g; - provider.darksky.progress = (regexDaily.test(config.show.template.detail) || regexHourly.test(config.show.template.detail)) ? 0 : 2; - } - record(`h_n:${provider.heweather_now.progress},h_d:${provider.heweather_daily.progress},h_a:${provider.heweather_air.progress},h_l:${provider.heweather_lifestyle.progress},aq:${provider.aqicn.progress},da:${provider.darksky.progress}`) -} -/** - * 用于普通模板的映射 - * @param {String} template 模板内容 - * @param {Object} map 映射内容 - */ -function execTemplate(template, map) { - if (!template) return ""; - let regex = /\$\[([a-z,A-Z,0-9]*)\]/g; - if (regex.test(template)) { - for (item of template.match(regex)) { - item.match(regex); - if (RegExp.$1 && map[RegExp.$1]) { - template = template.replace(item, map[RegExp.$1]); - } else { - template = template.replace(item, ""); - } - } - } - return template; -} - -function execArrayTemplate() { - try { - execTemplateLifestyle(); - execTemplateDaily(); - execTemplateHourly(); - } catch (e) { - console.log(`${JSON.stringify(e)}`) - } - -} - -function execTemplateLifestyle() { - let regexLifestyle = /\$\[(lifeStyle\()+([\s\S]+?)(\))+\]/g; - if (provider.heweather_lifestyle.data <= 0) { - config.show.template.detail.replace(regexLifestyle, '') - } - let result = []; - if (regexLifestyle.test(config.show.template.detail)) { - let lsMap = { //此处用于显示各项生活指数,可自行调整顺序,顺序越在前面则显示也会靠前,如果您不想查看某一指数,置为false即可,想看置为true即可 - drsg: { - icon: '👔穿衣指数', - type: '穿衣指数' - }, - flu: { - icon: '🤧感冒等级💉', - type: '感冒指数' - }, - comf: { - icon: '😊舒适度', - type: '舒适度指数' - }, - cw: { - icon: '🚗洗车', - type: '洗车指数' - }, - sport: { - icon: '🏃🏻运动', - type: '运动指数' - }, - trav: { - icon: '🌴', - type: '旅游指数' - }, - uv: { - icon: '☂️', - type: '紫外线指数' - }, - air: { - icon: '🌫', - type: '空气污染扩散条件指数' - }, - ac: { - icon: '❄️', - type: '空调开启指数' - }, - ag: { - icon: '😷', - type: '过敏指数' - }, - gl: { - icon: '🕶', - type: '太阳镜指数' - }, - mu: { - icon: '💄', - type: '化妆指数' - }, - airc: { - icon: '🧺', - type: '晾晒指数' - }, - ptfc: { - icon: '🚥', - type: '交通指数' - }, - fsh: { - icon: '🎣', - type: '钓鱼指数' - }, - spi: { - icon: '🔆', - type: '防晒指数' - }, - } - config.show.template.detail.match(regexLifestyle); - var rangeTemplate = RegExp.$2; //此处拿到的是要替换的列表显示部分了 - let regex = /\$\[([a-z,A-Z,0-9]*)\]/g; - var template = rangeTemplate.match(regex); - for (life of provider.heweather_lifestyle.data) { - if (!config.show.lifestyle[life.type]) continue; - var singleInfo = rangeTemplate; - for (item of template) { - item.match(regex); - if (RegExp.$1 == "icon") { - singleInfo = singleInfo.replace(item, lsMap[life.type].icon) - } else if (RegExp.$1 == "type") { - singleInfo = singleInfo.replace(item, lsMap[life.type].type) - } else { - singleInfo = singleInfo.replace(item, life[RegExp.$1]) - } - } - result.push(singleInfo); - } - config.show.template.detail = config.show.template.detail.replace(regexLifestyle, result.join(lineBreak)); - } -} - -function execTemplateDaily() { - let regexDaily = /\$\[(daily\()+([\s\S]+?)(\))+\]/g; - if (provider.darksky.data.daily.data.length <= 0) { - config.show.template.detail.replace(regexDaily, '') - } - let result = []; - if (regexDaily.test(config.show.template.detail)) { - config.show.template.detail.match(regexDaily); - var rangeTemplate = RegExp.$2; //此处拿到的是要替换的列表显示部分了 - let regex = /\$\[([a-z,A-Z,0-9]*)\]/g; - var template = rangeTemplate.match(regex); - for (daily of provider.darksky.data.daily.data) { - var singleInfo = rangeTemplate; - for (item of template) { - item.match(regex); - if (RegExp.$1 == "month") { - singleInfo = singleInfo.replace(item, (`${daily["time"]}`).toDateTime().Format("MM")); - } else if (RegExp.$1 == "day") { - singleInfo = singleInfo.replace(item, (`${daily["time"]}`).toDateTime().Format("dd")); - } else if (RegExp.$1 == "weatherIcon") { - singleInfo = singleInfo.replace(item, getDarkskyWeatherIcon(daily.icon)); - } else if (RegExp.$1 == "weather") { - singleInfo = singleInfo.replace(item, getDarkskyWeatherDesc(daily.icon)); - } else if (RegExp.$1 == "uvDesc") { - singleInfo = singleInfo.replace(item, getUVDesc(daily.uvIndex)); - } else if (RegExp.$1 == "cloudCover") { - singleInfo = singleInfo.replace(item, daily.cloudCover * 100); - } else if (RegExp.$1 == "temperatureHigh") { - singleInfo = singleInfo.replace(item, Math.round(daily.temperatureHigh)); - } else if (RegExp.$1 == "temperatureLow") { - singleInfo = singleInfo.replace(item, Math.round(daily.temperatureLow)); - } else if (RegExp.$1 == "apparentTemperatureMax") { - singleInfo = singleInfo.replace(item, Math.round(daily.apparentTemperatureMax)); - } else if (RegExp.$1 == "apparentTemperatureMin") { - singleInfo = singleInfo.replace(item, Math.round(daily.apparentTemperatureMin)); - } else if (RegExp.$1 && daily[RegExp.$1] != undefined) { - singleInfo = singleInfo.replace(item, daily[RegExp.$1]); - } - } - result.push(singleInfo); - } - config.show.template.detail = config.show.template.detail.replace(regexDaily, result.join(lineBreak)); - } -} - -function execTemplateHourly() { - let regexHourly = /\$\[(hourly\()+([\s\S]+?)(\))+\]/g; - if (provider.darksky.data.hourly.data.length <= 0) { - config.show.template.detail.replace(regexHourly, '') - } - let result = []; - if (regexHourly.test(config.show.template.detail)) { - config.show.template.detail.match(regexHourly); - var rangeTemplate = RegExp.$2; //此处拿到的是要替换的列表显示部分了 - let regex = /\$\[([a-z,A-Z,0-9]*)\]/g; - var template = rangeTemplate.match(regex); - for (hourly of provider.darksky.data.hourly.data) { - var singleInfo = rangeTemplate; - for (item of template) { - item.match(regex); - if (RegExp.$1 == "month") { - singleInfo = singleInfo.replace(item, (`${hourly["time"]}`).toDateTime().Format("MM")); - } else if (RegExp.$1 == "day") { - singleInfo = singleInfo.replace(item, (`${hourly["time"]}`).toDateTime().Format("dd")); - } else if (RegExp.$1 == "hour") { - singleInfo = singleInfo.replace(item, (`${hourly["time"]}`).toDateTime().Format("hh")); - } else if (RegExp.$1 == "weatherIcon") { - singleInfo = singleInfo.replace(item, getDarkskyWeatherIcon(hourly.icon)); - } else if (RegExp.$1 == "weather") { - singleInfo = singleInfo.replace(item, getDarkskyWeatherDesc(hourly.icon)); - } else if (RegExp.$1 == "uvDesc") { - singleInfo = singleInfo.replace(item, getUVDesc(hourly.uvIndex)); - } else if (RegExp.$1 == "cloudCover") { - singleInfo = singleInfo.replace(item, hourly.cloudCover * 100); - } else if (RegExp.$1 == "temperature") { - singleInfo = singleInfo.replace(item, Math.round(hourly.temperature)); - } else if (RegExp.$1 == "apparentTemperature") { - singleInfo = singleInfo.replace(item, Math.round(hourly.apparentTemperature)); - } else if (RegExp.$1 && hourly[RegExp.$1] != undefined) { - singleInfo = singleInfo.replace(item, hourly[RegExp.$1]); - } - } - result.push(singleInfo); - } - config.show.template.detail = config.show.template.detail.replace(regexHourly, result.join(lineBreak)); - } -} - -function record(log) { - if (config.log == 1) { - console.log(log); - } else if (config.log == 2) { - console.log(log.substring(0, 60)); - } -} -// #endregion - -// #region 扩展方法 -Array.prototype.get = function (index, defaultValue = {}) { - if (index >= 0 && this.length > 0 && this.length >= index + 1) { - return this[index]; - } else { - return defaultValue; - } -} -String.prototype.toDateTime = function () { - var time = parseInt(this + '000'); - return new Date(time); -} -Date.prototype.Format = function (fmt) { - var o = { - "M+": this.getMonth() + 1, //月份 - "d+": this.getDate(), //日 - "h+": this.getHours(), //小时 - "m+": this.getMinutes(), //分 - "s+": this.getSeconds(), //秒 - "q+": Math.floor((this.getMonth() + 3) / 3), //季度 - "S": this.getMilliseconds() //毫秒 - }; - if (/(y+)/.test(fmt)) - fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length)); - for (var k in o) - if (new RegExp("(" + k + ")").test(fmt)) - fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length))); - return fmt; -} -// #endregion -weather(); \ No newline at end of file