From 7bd2c087f43ab4a314521aac3db0b1724b818d66 Mon Sep 17 00:00:00 2001 From: bangbang93 Date: Thu, 5 Mar 2020 10:02:54 +0800 Subject: [PATCH] =?UTF-8?q?=E6=8E=89=E7=BA=BF=E8=87=AA=E5=8A=A8=E9=87=8D?= =?UTF-8?q?=E8=BF=9E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/bootstrap.ts | 4 ---- src/cluster.ts | 41 ++++++++++++++++++++++++++++------------- 2 files changed, 28 insertions(+), 17 deletions(-) diff --git a/src/bootstrap.ts b/src/bootstrap.ts index b51b958..69ff132 100644 --- a/src/bootstrap.ts +++ b/src/bootstrap.ts @@ -1,5 +1,4 @@ import * as colors from 'colors/safe' -import * as got from 'got' import {Cluster} from './cluster' import ms = require('ms') @@ -21,9 +20,6 @@ export async function bootstrap(version: string): Promise { try { await cluster.enable() } catch (e) { - if (e instanceof got.HTTPError) { - console.error(e.response.body) - } console.error(e) process.exit(1) } diff --git a/src/cluster.ts b/src/cluster.ts index da43e52..39da267 100644 --- a/src/cluster.ts +++ b/src/cluster.ts @@ -24,6 +24,7 @@ interface ICounters { export class Cluster { public readonly counters: ICounters = {hits: 0, bytes: 0} + public isEnabled = false private readonly prefixUrl = process.env.CLUSTER_BMCLAPI || 'https://openbmclapi.bangbang93.com' private readonly cacheDir = join(__dirname, '..', 'cache') @@ -62,10 +63,6 @@ export class Cluster { clusterId: this.clusterId, clusterSecret: this.clusterSecret, }, }) - this.io.on('connect', () => console.log('connected')) - this.io.on('message', (msg) => console.log(msg)) - this.io.on('disconnect', () => console.log('disconnect')) - this.io.on('error', (err) => console.error(err)) } public async getFileList(): Promise { @@ -139,16 +136,21 @@ export class Cluster { } public async enable(): Promise { - return new Promise((resolve, reject) => { - this.io.emit('enable', { - host: this.host, - port: this.publicPort, - version: this.version, - }, (ack) => { - if (ack !== true) return reject(ack) - resolve() - }) + if (this.isEnabled) return + if (this.io.connected) { + await this._enable() + } + this.io.on('connect', async () => { + console.log('connected') + await this._enable() + this.isEnabled = true + }) + this.io.on('message', (msg) => console.log(msg)) + this.io.on('disconnect', () => { + console.log('disconnect') + this.isEnabled = false }) + this.io.on('error', (err) => console.error(err)) } public async disable(): Promise { @@ -184,4 +186,17 @@ export class Cluster { }) }) } + + private async _enable() { + return new Promise((resolve, reject) => { + this.io.emit('enable', { + host: this.host, + port: this.publicPort, + version: this.version, + }, (ack) => { + if (ack !== true) return reject(ack) + resolve() + }) + }) + } }