Code Monkey home page Code Monkey logo

bilive_client's People

Contributors

bugkun avatar lzghzr avatar putegg avatar shmilychen avatar tzhongyan avatar vector000 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

bilive_client's Issues

报错:SyntaxError: Unexpected end of JSON input

第一遍run的时候没问题,重新编译再跑的时候报错:

undefined:1

SyntaxError: Unexpected end of JSON input
    at JSON.parse (<anonymous>)
    at new Options (/home/ubuntu/bilive_client/build/options.js:50:33)
    at Object.<anonymous> (/home/ubuntu/bilive_client/build/options.js:91:19)
    at Module._compile (internal/modules/cjs/loader.js:701:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
    at Module.load (internal/modules/cjs/loader.js:600:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
    at Function.Module._load (internal/modules/cjs/loader.js:531:3)
    at Module.require (internal/modules/cjs/loader.js:637:17)
    at require (internal/modules/cjs/helpers.js:22:18)

节奏风暴返回过期却继续尝试

如题
就今天遇到了
输出:
May 14 2019 21:44:54 : ID 节奏风暴 1098378443337 第3次尝试 你错过了奖励,下次要更快一点哦~
May 14 2019 21:44:55 : ID 节奏风暴 1098378443337 第4次尝试 节奏风暴抽奖过期
May 14 2019 21:44:55 : ID 节奏风暴 1098378443337 第5次尝试 节奏风暴抽奖过期

443错误

Jun 01 2019 23:29:05 : 已加载: 宝箱道具, 用于: 领取宝箱道具, 版本: 0.0.1, 作者:
lzghzr
Jun 01 2019 23:29:11 : https://data.bilibili.com/gv/ { Error: connect ECONNREFUS
ED 127.0.0.1:443
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1097:14)
errno: 'ECONNREFUSED',
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 443 }
Jun 01 2019 23:29:16 : https://data.bilibili.com/gv/ { Error: connect ECONNREFUS
ED 127.0.0.1:443
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1097:14)
errno: 'ECONNREFUSED',
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 443 }

请问这个怎么解决

最近经常出现的错误

Oct 15 2019 19:05:42 : https://api.live.bilibili.com/lottery/v2/lottery/join { Error: connect ETIMED
OUT 服务器IP地址:443
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1106:14)
errno: 'ETIMEDOUT',
code: 'ETIMEDOUT',
syscall: 'connect',
address: '服务器IP地址',
port: 443 }

虽然不会使脚本停止,但好像会使部分功能间歇性失效,比如自动领取银瓜子

请问PM2如何启动此项目

之前听说你这边把PM2弄好了,但是我试了却又是不行的,请问要如何启动呢?
建议在项目中配置一个PM2.json方便PM2的用户快速启动此项目

今天突然键入npm start出现错误,请问怎么办

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] build:view: webpack --config docs/webpack.conf.js && npm-run-posix-or-windows copy:view
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] build:view script.
npm ERR! This is probably not a problem with npm. There is likely additional log
ging output above.

npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\chy\AppData\Roaming\npm-cache_logs\2019-05-10T01_44_13_18
3Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] prestart: npm run clean && npm run build:view && n pm-run-posix-or-windows copy:client
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] prestart script.
npm ERR! This is probably not a problem with npm. There is likely additional log
ging output above.

npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\chy\AppData\Roaming\npm-cache_logs\2019-05-10T01_44_13_22
0Z-debug.log

下面是那两个日志
0 info it worked if it ends with ok
1 verbose cli [ 'F:\node.js\node.exe',
1 verbose cli 'F:\node.js\node_modules\npm\bin\npm-cli.js',
1 verbose cli 'run',
1 verbose cli 'build:view' ]
2 info using [email protected]
3 info using [email protected]
4 verbose run-script [ 'prebuild:view', 'build:view', 'postbuild:view' ]
5 info lifecycle [email protected]prebuild:view: [email protected]
6 info lifecycle [email protected]
build:view: [email protected]
7 verbose lifecycle [email protected]build:view: unsafe-perm in lifecycle true
8 verbose lifecycle [email protected]
build:view: PATH: F:\node.js\node_modules\npm\node_modules\npm-lifecycle\node-gyp-bin;F:\bilive_client\node_modules.bin;F:\node.js\node_modules\npm\node_modules\npm-lifecycle\node-gyp-bin;F:\bilive_client\node_modules.bin;F:\Python\Scripts;F:\Python;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0;F:\node.js;F:\Git\Git\cmd;C:\Users\chy\AppData\Roaming\npm
9 verbose lifecycle [email protected]build:view: CWD: F:\bilive_client
10 silly lifecycle [email protected]
build:view: Args: [ '/d /s /c',
10 silly lifecycle 'webpack --config docs/webpack.conf.js && npm-run-posix-or-windows copy:view' ]
11 silly lifecycle [email protected]build:view: Returned: code: 1 signal: null
12 info lifecycle [email protected]
build:view: Failed to exec build:view script
13 verbose stack Error: [email protected] build:view: webpack --config docs/webpack.conf.js && npm-run-posix-or-windows copy:view
13 verbose stack Exit status 1
13 verbose stack at EventEmitter. (F:\node.js\node_modules\npm\node_modules\npm-lifecycle\index.js:301:16)
13 verbose stack at EventEmitter.emit (events.js:189:13)
13 verbose stack at ChildProcess. (F:\node.js\node_modules\npm\node_modules\npm-lifecycle\lib\spawn.js:55:14)
13 verbose stack at ChildProcess.emit (events.js:189:13)
13 verbose stack at maybeClose (internal/child_process.js:970:16)
13 verbose stack at Process.ChildProcess._handle.onexit (internal/child_process.js:259:5)
14 verbose pkgid [email protected]
15 verbose cwd F:\bilive_client
16 verbose Windows_NT 6.3.9600
17 verbose argv "F:\node.js\node.exe" "F:\node.js\node_modules\npm\bin\npm-cli.js" "run" "build:view"
18 verbose node v10.15.3
19 verbose npm v6.4.1
20 error code ELIFECYCLE
21 error errno 1
22 error [email protected] build:view: webpack --config docs/webpack.conf.js && npm-run-posix-or-windows copy:view
22 error Exit status 1
23 error Failed at the [email protected] build:view script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 1, true ]

0 info it worked if it ends with ok
1 verbose cli [ 'F:\node.js\node.exe',
1 verbose cli 'F:\node.js\node_modules\npm\bin\npm-cli.js',
1 verbose cli 'start' ]
2 info using [email protected]
3 info using [email protected]
4 verbose run-script [ 'prestart', 'start', 'poststart' ]
5 info lifecycle [email protected]prestart: [email protected]
6 verbose lifecycle [email protected]
prestart: unsafe-perm in lifecycle true
7 verbose lifecycle [email protected]prestart: PATH: F:\node.js\node_modules\npm\node_modules\npm-lifecycle\node-gyp-bin;F:\bilive_client\node_modules.bin;F:\Python\Scripts;F:\Python;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0;F:\node.js;F:\Git\Git\cmd;C:\Users\chy\AppData\Roaming\npm
8 verbose lifecycle [email protected]
prestart: CWD: F:\bilive_client
9 silly lifecycle [email protected]prestart: Args: [ '/d /s /c',
9 silly lifecycle 'npm run clean && npm run build:view && npm-run-posix-or-windows copy:client' ]
10 silly lifecycle [email protected]
prestart: Returned: code: 1 signal: null
11 info lifecycle [email protected]~prestart: Failed to exec prestart script
12 verbose stack Error: [email protected] prestart: npm run clean && npm run build:view && npm-run-posix-or-windows copy:client
12 verbose stack Exit status 1
12 verbose stack at EventEmitter. (F:\node.js\node_modules\npm\node_modules\npm-lifecycle\index.js:301:16)
12 verbose stack at EventEmitter.emit (events.js:189:13)
12 verbose stack at ChildProcess. (F:\node.js\node_modules\npm\node_modules\npm-lifecycle\lib\spawn.js:55:14)
12 verbose stack at ChildProcess.emit (events.js:189:13)
12 verbose stack at maybeClose (internal/child_process.js:970:16)
12 verbose stack at Process.ChildProcess._handle.onexit (internal/child_process.js:259:5)
13 verbose pkgid [email protected]
14 verbose cwd F:\bilive_client
15 verbose Windows_NT 6.3.9600
16 verbose argv "F:\node.js\node.exe" "F:\node.js\node_modules\npm\bin\npm-cli.js" "start"
17 verbose node v10.15.3
18 verbose npm v6.4.1
19 error code ELIFECYCLE
20 error errno 1
21 error [email protected] prestart: npm run clean && npm run build:view && npm-run-posix-or-windows copy:client
21 error Exit status 1
22 error Failed at the [email protected] prestart script.
22 error This is probably not a problem with npm. There is likely additional logging output above.
23 verbose exit [ 1, true ]

音量全开

新活动 有个大乱斗PK ,每局胜利方开启“音量全开”抽奖,有几率获得金瓜子,必出辣条(好像)

关于登录状态

{ code: -401, data: null, message: '请先登录哦', msg: '请先登录哦' }
cookie 到期了有时候会登录不上,也不会重新登录,是否可以加个推送?
还有一个账号密码更改的bug,在原来的用户上直接更改不会生效,必须新建一个用户重新填写才行。

启动问题

输入npm start后显示error TS6059: File 'D:/git/Git/bilive_client/app.ts' is not under 'rootDir' 'D:/git/Git/bilive_client/bilive'. 'rootDir' is expected to contain all source files.

12:30:04 - Found 1 error. Watching for file changes.
这个怎么办?

大佬有空的话可以优化一下这些方面吗?

这两天提交了两个PR,肝不动了。。。

  • 建议优化一下package.json,让用户可以使用npm install --production,来减少模块的安装,减少程序的体积。
  • 现在的项目自动更新方面还有优化的空间,建议通过子线程的方式运行项目,主线程操作自动更新。减少git pull自动更新带来的历史版本对空间的占用。

关于消息问题

每次启动都会显示服务器11月到期,这个是什么意思?

安卓Termux挂机更新检测问题

安卓手机可以通过安装termux进行挂机,但是会出现"WARNING: linker: Unsupported flags DT_FLAGS_1=0x8"导致更新检测失败,但是报错出现后才开始获取+返回

抽奖暂停问题

一早起来发现黑了,这次才出来了一个晚上,我记得我设置了凌晨到早上这几个小时不抽的,查了下日志,我设置的是(3,4,5,6,7,8),在3-4点的时间段内确实是停止了抽奖,但是从4点开始往后就又开始抽了,然后我在6点的时候就黑了。。。

关于节奏风暴

多个节奏风暴同时抽奖非常容易被判定412
能否添加功能控制单个用户同时抽的节奏风暴的数量

签到接口下线

自动签到 { code: -1, msg: '该接口已下线', message: '该接口已下线', data: [] }

礼物刷屏

连续的百来个小电视,基本只能抽到10-20%左右,其余的基本请求频繁了

晚上会出现一些状况

有时会只领舰队不领活动抽奖。(比如现在)
有时候会全部网络错误,持续一小时(或几小时 反正是以60分钟为单位)
出现在晚上23点为多,
重启服务器没用,其他人会有这种情况吗?

403拒绝访问

{ code: -403, data: null, message: '访问被拒绝', msg: '访问被拒绝' }
这阵子有了403拒绝访问,然后自动禁抽跟推送就GG了

有讨论群吗

如图,非敲代码的我有些看不懂操作 想找大佬也找不到人

Error: read ECONNRESET

Jun 15 2019 23:57:09 : Error: read ECONNRESET
at TLSWrap.onStreamRead (internal/stream_base_commons.js:183:27) {
errno: 'ECONNRESET',
code: 'ECONNRESET',
syscall: 'read'
}

自动更新出现问题

自动更新出现这些,这要怎么操作啊,大佬?

环境

Xiaomi 9 SE _ MIUI 10 _ Android 9
Termux

出现的问题

May 12 2019 11:03:42 : Error: Command failed: git merge
error: Your local changes to the following files would be overwritten by merge:
        bilive/@types/bilive.d.ts
        bilive/lib/tools.ts
        bilive/options.default.json
        bilive/options.ts
        bilive/webapi.ts
        docs/index.html
        docs/options.ts
        docs/script.ts
        package.json
Please commit your changes or stash them before you merge.
Aborting

    at ChildProcess.exithandler (child_process.js:304:12)
    at ChildProcess.emit (events.js:196:13)
    at maybeClose (internal/child_process.js:1011:16)
    at Socket.<anonymous> (internal/child_process.js:416:11)
    at Socket.emit (events.js:196:13)
    at Pipe.<anonymous> (net.js:586:12) {
  killed: false,
  code: 1,
  signal: null,
  cmd: 'git merge'
}
May 12 2019 11:03:42 : error: Your local changes to the following files would be overwritten by merge:
        bilive/@types/bilive.d.ts
        bilive/lib/tools.ts
        bilive/options.default.json
        bilive/options.ts
        bilive/webapi.ts
        docs/index.html
        docs/options.ts
        docs/script.ts
        package.json
Please commit your changes or stash them before you merge.
Aborting

git pull
Updating ecd01f2..56abde9
error: Your local changes to the following files would be overwritten by merge:
        bilive/@types/bilive.d.ts
        bilive/lib/tools.ts
        bilive/options.default.json
        bilive/options.ts
        bilive/webapi.ts
        docs/index.html
        docs/options.ts
        docs/script.ts
        package.json
Please commit your changes or stash them before you merge.
Aborting

监听错误

at TLSWrap.onStreamRead (internal/stream_base_commons.js:111:27) errno: 'ECONNRESET', code: 'ECONNRESET', syscall: 'read' }

黑屋检测不够频密

批量挂号的时候,各个号进出黑屋的时间都不固定,现在的检测出屋的频率太低了,有时候刚检测一次过几分钟就出了黑屋,漏了很多亲密和辣条,建议检测频率提高到每个小时或每半个小时就检测一次

关于加密

最近添加了netkey加密,然后发现导出的日志文本也是加密的,这样查看起来有点不方便

Web Api 支持

由于已经fork了主分支。。。在这里点fork不知道怎么总是跳我那个主分支的fork。。。就不知道怎么pull到你这里了。。

需要添加一下包

{
    "@types/express": "^4.17.0",
    "body-parser": "^1.19.0",
    "express": "^4.17.1",
}

替换文件 webapi.ts 并重新编译

import ws from 'ws'
import fs from 'fs'
import http from 'http'
import {randomBytes} from 'crypto'
import {EventEmitter} from 'events'
import tools from './lib/tools'
import User from './online'
import Options from './options'
import express = require('express');

/**
 * 程序设置
 *
 * @class WebAPI
 * @extends {EventEmitter}
 */
class WebAPI extends EventEmitter {
    constructor() {
        super()
    }

    private _wsClient!: ws;

    /**
     * 启动HTTP以及WebSocket服务
     *
     * @memberof WebAPI
     */
    public Start() {
        this._HttpServer()
    }

    /**
     * HTTP服务
     *
     * @private
     * @memberof WebAPI
     */
    private _HttpServer() {
        // 监听 HTTP API
        this._listenAPI(Options._.server);

        // 直接跳转到github.io, 为防以后变更使用302
        const server = http.createServer((req, res) => {
            req.on('error', error => tools.ErrorLog('req', error));
            res.on('error', error => tools.ErrorLog('res', error));
            res.writeHead(302, {'Location': '//github.halaal.win/bilive_client/'});
            res.end()
        }).on('error', error => tools.ErrorLog('http', error));
        // 监听地址优先支持Unix Domain Socket
        const listen = Options._.server;
        if (listen.path === '') {
            const host = process.env.HOST === undefined ? listen.hostname : process.env.HOST;
            const port = process.env.PORT === undefined ? listen.port : Number.parseInt(<string>process.env.PORT);
            server.listen(port, host, () => {
                this._WebSocketServer(server);
                tools.Log(`已监听 ${host}:${port}`)
            })
        } else {
            if (fs.existsSync(listen.path)) fs.unlinkSync(listen.path);
            server.listen(listen.path, () => {
                fs.chmodSync(listen.path, '666');
                this._WebSocketServer(server);
                tools.Log(`已监听 ${listen.path}`)
            })
        }
    }

    private _listenAPI(listen: server) {
        const bodyParser = require('body-parser');
        const app: express.Application = express();
        app.use(bodyParser.json());

        /**
         * 解决跨域
         */
        app.all('*', function (_req, res, next) {
            res.setHeader("Access-Control-Allow-Origin", "*");
            res.setHeader("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
            res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
            next();
        });
        /**
         * 拦截所有 GET
         */
        app.get('*', function (_req, res) {
            tools.Log('API ==> ' + 'GET 访问全部拦截');
            res.redirect("http://github.halaal.win/bilive_client/");
        });

        const _ = this;

        /**
         * 处理所有的 post
         */
        app.post('/', async function (req, res) {
            res.setHeader('Content-Type', 'application/json;charset=utf-8');

            const authorization = req.get('Authorization');
            const cmd = req.get('Action');

            // 初始化返回
            let sendData = {
                code: 500,
                data: {},
                msg: '没有密钥'
            };

            if (!cmd) {
                sendData.msg = '没有操作';
            }

            if (authorization === listen.protocol && cmd) {
                tools.Log('API ==> 密钥正确,需要进行:' + cmd);
                sendData.code = 200;
                sendData.msg = 'success';
                const message = <message>req.body;
                const data = _._processHttp(message, cmd);
                sendData = Object.assign(sendData, data);
            }
            res.send(sendData);
        });

        const port = process.env.APIPORT === undefined ? 2020 : Number.parseInt(<string>process.env.APIPORT);
        app.listen(port, function () {
            tools.Log('API ==> ' + '监听端口' + port);
        });
    }

    private _processHttp(message: message, action: string) {
        const cmd = action;
        const ts = message.ts;
        let respond;
        switch (cmd) {
            // 获取所有操作方法
            case 'getAction': {
                respond = {
                    cmd,
                    ts,
                    data: ['getAction', 'getLog', 'getConfig', 'setConfig', 'getInfo', 'getAllUID', 'getUserData', 'setUserData', 'delUserData', 'newUserData']
                };
            }
                break;
            // 获取log
            case 'getLog': {
                const data = this.wsGetLog();
                respond = {cmd, ts, data};
            }
                break;
            // 获取设置
            case 'getConfig': {
                const data = this.wsGetConfig();
                respond = {cmd, ts, data};
            }
                break;
            // 保存设置
            case 'setConfig': {
                const data = this.wsSetConfig(message);
                respond = {cmd, ts, ...data};
            }
                break;
            // 获取参数描述
            case 'getInfo': {
                const data = this.wsGetInfo();
                respond = {cmd, ts, data};
            }
                break;
            // 获取uid
            case 'getAllUID': {
                const data = this.wsGetAllUId();
                respond = {cmd, ts, data};
            }
                break;
            // 获取用户设置
            case 'getUserData': {
                const data = this.wsGetUserDataById(message);
                respond = {cmd, ts, ...data};
            }
                break;
            // 保存用户设置
            case 'setUserData': {
                const data = this.wsSetUserDataById(message);
                respond = {cmd, ts, ...data};
            }
                break;
            // 删除用户设置
            case 'delUserData': {
                const data = this.wsDelUserDataById(message);
                respond = {cmd, ts, ...data};
            }
                break;
            // 新建用户设置
            case 'newUserData': {
                const data = this.wsCreateUserData();
                respond = {cmd, ts, ...data};
            }
                break;
            // 未知命令

            default:
                respond = {cmd, ts, msg: '未知命令'};
                break
        }
        return respond;
    }

    /**
     * WebSocket服务
     *
     * @private
     * @param {http.Server} server
     * @memberof WebAPI
     */
    private _WebSocketServer(server: http.Server) {
        const WSserver = new ws.Server({
            server,
            verifyClient: (info: { origin: string, req: http.IncomingMessage, secure: boolean }) => {
                const protocol = info.req.headers['sec-websocket-protocol'];
                const adminProtocol = Options._.server.protocol;
                return protocol === adminProtocol;
            }
        });
        WSserver.on('error', error => tools.ErrorLog('websocket', error))
            .on('connection', (client: ws, req: http.IncomingMessage) => {
                // 使用Nginx可能需要
                const remoteAddress = req.headers['x-real-ip'] === undefined
                    ? `${req.connection.remoteAddress}:${req.connection.remotePort}`
                    : `${req.headers['x-real-ip']}:${req.headers['x-real-port']}`;
                tools.Log(`${remoteAddress} 已连接`);
                // 限制同时只能连接一个客户端
                if (this._wsClient !== undefined) this._wsClient.close(1001, JSON.stringify({
                    cmd: 'close',
                    msg: 'too many connections'
                }));
                // 使用function可能出现一些问题, 此处无妨
                const onLog = (data: string) => this._Send({cmd: 'log', ts: 'log', msg: data});
                const destroy = () => {
                    tools.removeListener('log', onLog);
                    client.close();
                    client.terminate();
                    client.removeAllListeners()
                };
                client
                    .on('error', (error) => {
                        destroy();
                        tools.ErrorLog('client', error)
                    })
                    .on('close', (code, reason) => {
                        destroy();
                        tools.Log(`${remoteAddress} 已断开`, code, reason)
                    })
                    .on('message', async (msg: string) => {
                        const message = await tools.JSONparse<message>(msg);
                        if (message !== undefined && message.cmd !== undefined && message.ts !== undefined) this._onCMD(message);
                        else this._Send({cmd: 'error', ts: 'error', msg: '消息格式错误'})
                    });
                // 一般推荐客户端发送心跳, 不过放在服务端的话可以有一些限制 (目前没有)
                const ping = setInterval(() => {
                    if (client.readyState === ws.OPEN) client.ping();
                    else clearInterval(ping)
                }, 60 * 1000); // 60s为Nginx默认的超时时间
                this._wsClient = client;
                // 日志
                tools.on('log', onLog)
            })
    }

    private wsGetLog() {
        return tools.logs;
    }

    private wsGetConfig() {
        return Options._.config;
    }

    private wsSetConfig(message: message) {
        const config = Options._.config;
        const serverURL = config.serverURL;
        const setConfig = <config>message.data || {};
        let msg = '';
        for (const i in config) {
            if (typeof config[i] !== typeof setConfig[i]) {
                // 一般都是自用, 做一个简单的验证就够了
                msg = i + '参数错误';
                break
            }
        }
        if (msg === '') {
            // 防止setConfig里有未定义属性, 不使用Object.assign
            for (const i in config) config[i] = setConfig[i];
            Options.save();
            if (serverURL !== config.serverURL) Options.emit('clientUpdate');
            return {data: config}
        } else return {msg, data: config}
    }

    private wsGetInfo() {
        return Options._.info;
    }

    private wsGetAllUId() {
        return Object.keys(Options._.user);
    }

    private wsGetUserDataById(message: message) {
        const user = Options._.user;
        const getUID = message.uid;
        if (typeof getUID === 'string' && user[getUID] !== undefined) {
            return {
                uid: getUID,
                data: user[getUID]
            };
        } else {
            return {msg: '未知用户'}
        }
    }

    private wsDelUserDataById(message: message) {
        const user = Options._.user;
        const delUID = message.uid;
        if (delUID !== undefined && user[delUID] !== undefined) {
            const userData = user[delUID];
            delete Options._.user[delUID];
            if (Options.user.has(delUID)) (<User>Options.user.get(delUID)).Stop();
            Options.save();
            return {uid: delUID, data: userData};
        } else return {uid: delUID, msg: '未知用户'}
    }

    private async wsSetUserDataById(message: message) {
        const user = Options._.user;
        const setUID = message.uid;
        if (setUID !== undefined && user[setUID] !== undefined) {
            const userData = user[setUID];
            const setUserData = <userData>message.data || {};
            let msg = '';
            let captcha = '';
            for (const i in userData) {
                if (typeof userData[i] !== typeof setUserData[i]) {
                    msg = i + '参数错误';
                    break
                }
            }
            if (msg === '') {
                for (const i in userData) userData[i] = setUserData[i];
                if (userData.status && !Options.user.has(setUID)) {
                    // 因为使用了Map保存已激活的用户, 所以需要添加一次
                    const newUser = new User(setUID, userData);
                    const status = await newUser.Start();
                    // 账号会尝试登录, 如果需要验证码status会返回'captcha', 并且验证码会以DataUrl形式保存在captchaJPEG
                    if (status === 'captcha') captcha = newUser.captchaJPEG;
                    else if (Options.user.has(setUID)) Options.emit('newUser', newUser)
                } else if (userData.status && Options.user.has(setUID)) {
                    // 对于已经存在的用户, 可能处在验证码待输入阶段
                    const captchaUser = <User>Options.user.get(setUID);
                    if (captchaUser.captchaJPEG !== '' && message.captcha !== undefined) {
                        // 对于这样的用户尝试使用验证码登录
                        captchaUser.captcha = message.captcha;
                        const status = await captchaUser.Start();
                        if (status === 'captcha') captcha = captchaUser.captchaJPEG;
                        else if (Options.user.has(setUID)) Options.emit('newUser', captchaUser)
                    }
                } else if (!userData.status && Options.user.has(setUID)) (<User>Options.user.get(setUID)).Stop();
                Options.save();
                if (captcha === '') return {uid: setUID, data: userData};
                else return {uid: setUID, msg: 'captcha', data: userData, captcha}
            } else return {uid: setUID, msg, data: userData}
        } else return {uid: setUID, msg: '未知用户'}
    }

    private wsCreateUserData() {
        const uid = randomBytes(16).toString('hex');
        const data = Object.assign({}, Options._.newUserData);
        Options.whiteList.add(uid);
        Options._.user[uid] = data;
        Options.save();
        return {uid, data}
    }

    /**
     *
     * 监听客户端发来的消息, CMD为关键字
     *
     * @private
     * @param {message} message
     * @memberof WebAPI
     */
    private async _onCMD(message: message) {
        const cmd = message.cmd;
        const ts = message.ts;
        switch (cmd) {
            // 获取log
            case 'getLog': {
                const data = this.wsGetLog();
                this._Send({cmd, ts, data})
            }
                break;
            // 获取设置
            case 'getConfig': {
                const data = this.wsGetConfig();
                this._Send({cmd, ts, data})
            }
                break;
            // 保存设置
            case 'setConfig': {
                const data = this.wsSetConfig(message);
                this._Send({cmd, ts, ...data})
            }
                break;
            // 获取参数描述
            case 'getInfo': {
                const data = this.wsGetInfo();
                this._Send({cmd, ts, data})
            }
                break;
            // 获取uid
            case 'getAllUID': {
                const data = this.wsGetAllUId();
                this._Send({cmd, ts, data})
            }
                break;
            // 获取用户设置
            case 'getUserData': {
                const data = this.wsGetUserDataById(message);
                this._Send({cmd, ts, ...data});
            }
                break;
            // 保存用户设置
            case 'setUserData': {
                const data = this.wsSetUserDataById(message);
                this._Send({cmd, ts, ...data});
            }
                break;
            // 删除用户设置
            case 'delUserData': {
                const data = this.wsDelUserDataById(message);
                this._Send({cmd, ts, ...data});
            }
                break;
            // 新建用户设置
            case 'newUserData': {
                const data = this.wsCreateUserData();
                this._Send({cmd, ts, ...data})
            }
                break;
            // 未知命令
            default:
                this._Send({cmd, ts, msg: '未知命令'});
                break
        }
    }

    /**
     * 向客户端发送消息
     *
     * @private
     * @param {message} message
     * @memberof WebAPI
     */
    private _Send(message: message) {
        if (this._wsClient.readyState === ws.OPEN) this._wsClient.send(JSON.stringify(message))
    }
}

// WebSocket消息
interface message {
    cmd: string
    ts: string
    msg?: string
    uid?: string
    data?: config | optionsInfo | string[] | userData
    captcha?: string
}

export default WebAPI
export {message}

主站投币的问题

最近好像获取不到关注列表?会弹出“视频列表空空的哦,去关注几个up主吧~”

更改账号顺序问题

我发现是按添加顺序抽奖了,由于我挂的比较多号,后面的号就比较慢,我想让一个号替换到前面的用户信息,在清空一个用户的信息并填入后保存出现弹窗 sendgifroom参数错误 这个我搞不懂...

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.