feat/fix: add disconnect/fix reconenct command

This commit is contained in:
iCrawl 2019-08-03 14:16:17 +02:00
parent 43cb3de14b
commit 7e8ea061aa
No known key found for this signature in database
GPG key ID: E41A6DB922EC2CFE
4 changed files with 46 additions and 34 deletions

View file

@ -7,7 +7,7 @@ import {
window window
} from 'vscode'; } from 'vscode';
import * as vsls from 'vsls'; import * as vsls from 'vsls';
import Activity from '../structures/Activity'; import Activity, { State } from '../structures/Activity';
import Logger from '../structures/Logger'; import Logger from '../structures/Logger';
const clipboardy = require('clipboardy'); // eslint-disable-line const clipboardy = require('clipboardy'); // eslint-disable-line
@ -66,27 +66,27 @@ export default class RPCClient implements Disposable {
await this._activity.disableJoinRequests(); await this._activity.disableJoinRequests();
} }
public async login(): Promise<void> { public async login(reconnect: boolean = false): Promise<void> {
if (this._rpc) return; if (this._rpc) return;
this._rpc = new Client({ transport: 'ipc' }); this._rpc = new Client({ transport: 'ipc' });
Logger.log('Logging into RPC.'); Logger.log('Logging into RPC.');
this._rpc.once('ready', async (): Promise<void> => { this._rpc.once('ready', async () => {
Logger.log('Successfully connected to Discord.'); Logger.log('Successfully connected to Discord.');
this.statusBarIcon.text = '$(globe) Connected to Discord'; this.statusBarIcon.text = '$(globe) Connected to Discord';
this.statusBarIcon.tooltip = 'Connected to Discord'; this.statusBarIcon.tooltip = 'Connected to Discord';
// @ts-ignore // @ts-ignore
setTimeout((): void => this.statusBarIcon.text = '$(globe)', 5000); setTimeout(() => this.statusBarIcon.text = '$(globe)', 5000);
if (activityTimer) clearInterval(activityTimer); if (activityTimer) clearInterval(activityTimer);
this.setActivity(); this.setActivity();
activityTimer = setInterval((): void => { activityTimer = setInterval(() => {
this.config = workspace.getConfiguration('discord'); this.config = workspace.getConfiguration('discord');
this.setActivity(this.config.get<boolean>('workspaceElapsedTime')); this.setActivity(this.config.get<boolean>('workspaceElapsedTime'));
}, 10000); }, 10000);
this._rpc.subscribe('ACTIVITY_SPECTATE', async ({ secret }: { secret: string }): Promise<void> => { this._rpc.subscribe('ACTIVITY_SPECTATE', async ({ secret }: { secret: string }) => {
const liveshare = await vsls.getApi(); const liveshare = await vsls.getApi();
if (!liveshare) return; if (!liveshare) return;
try { try {
@ -106,17 +106,17 @@ export default class RPCClient implements Disposable {
// You might be asking yourself again: "but why?" // You might be asking yourself again: "but why?"
// Same here, this is a real nasty race condition that happens inside the discord-rpc module currently // Same here, this is a real nasty race condition that happens inside the discord-rpc module currently
// To circumvent this we need to timeout sending the subscribe events to the discord client // To circumvent this we need to timeout sending the subscribe events to the discord client
setTimeout((): void => { setTimeout(() => {
this._rpc.subscribe('ACTIVITY_JOIN_REQUEST', async ({ user }: { user: { username: string; discriminator: string } }): Promise<void> => this._rpc.subscribe('ACTIVITY_JOIN_REQUEST', async ({ user }: { user: { username: string; discriminator: string } }) =>
window.showInformationMessage(`${user.username}#${user.discriminator} wants to join your session`, { title: 'Accept' }, { title: 'Decline' }) window.showInformationMessage(`${user.username}#${user.discriminator} wants to join your session`, { title: 'Accept' }, { title: 'Decline' })
// eslint-disable-next-line // eslint-disable-next-line
.then(async (val: { title: string } | undefined) => { .then(async (val: { title: string } | undefined) => {
if (val && val.title === 'Accept') await this._rpc.sendJoinInvite(user); // eslint-disable-line if (val && val.title === 'Accept') await this._rpc.sendJoinInvite(user); // eslint-disable-line
else await this._rpc.closeJoinRequest(user); else await this._rpc.closeJoinRequest(user);
})); }));
}, 500); }, 1000);
setTimeout((): void => { setTimeout(() => {
this._rpc.subscribe('ACTIVITY_JOIN', async ({ secret }: { secret: string }): Promise<void> => { this._rpc.subscribe('ACTIVITY_JOIN', async ({ secret }: { secret: string }) => {
const liveshare = await vsls.getApi(); const liveshare = await vsls.getApi();
if (!liveshare) return; if (!liveshare) return;
try { try {
@ -130,26 +130,24 @@ export default class RPCClient implements Disposable {
Logger.log(error); Logger.log(error);
} }
}); });
}, 1000); }, 2000);
const liveshare = await vsls.getApi(); const liveshare = await vsls.getApi();
if (!liveshare) return; if (!liveshare) return;
liveshare.onDidChangeSession(({ session }: { session: vsls.Session }): void => { liveshare.onDidChangeSession(({ session }: { session: vsls.Session }): State | void => {
// @ts-ignore
if (session.id) return this._activity.changePartyId(session.id); if (session.id) return this._activity.changePartyId(session.id);
// @ts-ignore
return this._activity.changePartyId(); return this._activity.changePartyId();
}); });
liveshare.onDidChangePeers(({ added, removed }: { added: vsls.Peer[]; removed: vsls.Peer[] }): void => { liveshare.onDidChangePeers(({ added, removed }: { added: vsls.Peer[]; removed: vsls.Peer[] }): State | void => {
// @ts-ignore
if (added.length) return this._activity.increasePartySize(added.length); if (added.length) return this._activity.increasePartySize(added.length);
// @ts-ignore
else if (removed.length) return this._activity.decreasePartySize(removed.length); else if (removed.length) return this._activity.decreasePartySize(removed.length);
}); });
}); });
this._rpc.transport.once('close', async (): Promise<void> => { this._rpc.transport.once('close', async () => {
if (!this.config.get<boolean>('enabled')) return; if (!this.config.get<boolean>('enabled')) return;
if (reconnect) return;
console.log('called close', reconnect);
await this.dispose(); await this.dispose();
this.statusBarIcon.text = '$(plug) Reconnect to Discord'; this.statusBarIcon.text = '$(plug) Reconnect to Discord';
this.statusBarIcon.command = 'discord.reconnect'; this.statusBarIcon.command = 'discord.reconnect';
@ -162,7 +160,7 @@ export default class RPCClient implements Disposable {
public async dispose(): Promise<void> { public async dispose(): Promise<void> {
this._activity.dispose(); this._activity.dispose();
try { try {
await this._rpc.destroy(); if (this._rpc) await this._rpc.destroy();
} catch {} } catch {}
this._rpc = null; this._rpc = null;
this.statusBarIcon.tooltip = ''; this.statusBarIcon.tooltip = '';

View file

@ -10,6 +10,8 @@ import RPCClient from './client/RPCClient';
import Logger from './structures/Logger'; import Logger from './structures/Logger';
const { register } = require('discord-rpc'); // eslint-disable-line const { register } = require('discord-rpc'); // eslint-disable-line
let loginTimeout: NodeJS.Timer;
const statusBarIcon: StatusBarItem = window.createStatusBarItem(StatusBarAlignment.Left); const statusBarIcon: StatusBarItem = window.createStatusBarItem(StatusBarAlignment.Left);
statusBarIcon.text = '$(pulse) Connecting to Discord...'; statusBarIcon.text = '$(pulse) Connecting to Discord...';
@ -50,7 +52,7 @@ export async function activate(context: ExtensionContext): Promise<void> {
} }
} }
const enabler = commands.registerCommand('discord.enable', async (): Promise<void> => { const enabler = commands.registerCommand('discord.enable', async () => {
await rpc.dispose(); await rpc.dispose();
config.update('enabled', true); config.update('enabled', true);
rpc.config = workspace.getConfiguration('discord'); rpc.config = workspace.getConfiguration('discord');
@ -60,7 +62,7 @@ export async function activate(context: ExtensionContext): Promise<void> {
window.showInformationMessage('Enabled Discord Rich Presence for this workspace.'); window.showInformationMessage('Enabled Discord Rich Presence for this workspace.');
}); });
const disabler = commands.registerCommand('discord.disable', async (): Promise<void> => { const disabler = commands.registerCommand('discord.disable', async () => {
config.update('enabled', false); config.update('enabled', false);
rpc.config = workspace.getConfiguration('discord'); rpc.config = workspace.getConfiguration('discord');
await rpc.dispose(); await rpc.dispose();
@ -68,31 +70,40 @@ export async function activate(context: ExtensionContext): Promise<void> {
window.showInformationMessage('Disabled Discord Rich Presence for this workspace.'); window.showInformationMessage('Disabled Discord Rich Presence for this workspace.');
}); });
const reconnecter = commands.registerCommand('discord.reconnect', async (): Promise<void> => { const reconnecter = commands.registerCommand('discord.reconnect', async () => {
if (loginTimeout) clearTimeout(loginTimeout);
await rpc.dispose(); await rpc.dispose();
await rpc.login(); loginTimeout = setTimeout(async () => {
if (!config.get('silent')) window.showInformationMessage('Reconnecting to Discord RPC...'); await rpc.login();
rpc.statusBarIcon.text = '$(pulse) Reconnecting to Discord...'; if (!config.get('silent')) window.showInformationMessage('Reconnecting to Discord RPC...');
rpc.statusBarIcon.command = undefined; rpc.statusBarIcon.text = '$(pulse) Reconnecting to Discord...';
rpc.statusBarIcon.command = 'discord.reconnect';
}, 1000);
}); });
const allowSpectate = commands.registerCommand('discord.allowSpectate', async (): Promise<void> => { const disconnect = commands.registerCommand('discord.disconnect', async () => {
await rpc.dispose();
rpc.statusBarIcon.text = '$(pulse) Reconnect to Discord';
rpc.statusBarIcon.command = 'discord.reconnect';
});
const allowSpectate = commands.registerCommand('discord.allowSpectate', async () => {
await rpc.allowSpectate(); await rpc.allowSpectate();
}); });
const disableSpectate = commands.registerCommand('discord.disableSpectate', async (): Promise<void> => { const disableSpectate = commands.registerCommand('discord.disableSpectate', async () => {
await rpc.disableSpectate(); await rpc.disableSpectate();
}); });
const allowJoinRequests = commands.registerCommand('discord.allowJoinRequests', async (): Promise<void> => { const allowJoinRequests = commands.registerCommand('discord.allowJoinRequests', async () => {
await rpc.allowJoinRequests(); await rpc.allowJoinRequests();
}); });
const disableJoinRequests = commands.registerCommand('discord.disableJoinRequests', async (): Promise<void> => { const disableJoinRequests = commands.registerCommand('discord.disableJoinRequests', async () => {
await rpc.disableJoinRequests(); await rpc.disableJoinRequests();
}); });
context.subscriptions.push(enabler, disabler, reconnecter, allowSpectate, disableSpectate, allowJoinRequests, disableJoinRequests); context.subscriptions.push(enabler, disabler, reconnecter, disconnect, allowSpectate, disableSpectate, allowJoinRequests, disableJoinRequests);
} }
export async function deactivate(): Promise<void> { export async function deactivate(): Promise<void> {

View file

@ -15,7 +15,7 @@ const knownLanguages: string[] = lang.knownLanguages;
const empty = '\u200b\u200b'; const empty = '\u200b\u200b';
const sizes = [' bytes', 'kb', 'mb', 'gb', 'tb']; const sizes = [' bytes', 'kb', 'mb', 'gb', 'tb'];
interface State { export interface State {
details?: string; details?: string;
state?: string; state?: string;
startTimestamp?: number | null; startTimestamp?: number | null;

View file

@ -26,9 +26,12 @@ module.exports = {
cache: false, cache: false,
parallel: true, parallel: true,
sourceMap: true, sourceMap: true,
extractComments: true,
terserOptions: { terserOptions: {
ecma: 8, ecma: 8,
keep_classnames: true mangle: false,
keep_classnames: true,
keep_fnames: true
} }
}) })
] ]