Skip to content

Commit

Permalink
feat: kubernetes detactor
Browse files Browse the repository at this point in the history
  • Loading branch information
RozmarinUS committed Jul 9, 2023
1 parent a197108 commit 1292e4b
Show file tree
Hide file tree
Showing 6 changed files with 241 additions and 235 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "discord-vscode-rpc",
"displayName": "Discord Rich Presence Connect",
"version": "1.0.6",
"version": "1.0.7",
"description": "Update your discord status with a rich presence.",
"private": true,
"author": {
Expand Down
15 changes: 10 additions & 5 deletions src/activity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
UNKNOWN_GIT_REPO_NAME,
VSCODE_IMAGE_KEY,
VSCODE_INSIDERS_IMAGE_KEY,
VSCODE_KUBERNETES_IMAGE_KEY,
} from './constants';
import { log, LogLevel } from './logger';
import { getConfig, getGit, resolveFileIcon, toLower, toTitle, toUpper } from './util';
Expand Down Expand Up @@ -161,11 +162,16 @@ export async function activity(previous: ActivityPayload = {}) {
const swapBigAndSmallImage = config[CONFIG_KEYS.SwapBigAndSmallImage];

const appName = env.appName;
const defaultSmallImageKey = debug.activeDebugSession
const remoteName = env.remoteName;
const isK8s = remoteName === 'k8s-container';
const defaultSmallImageKey = isK8s
? VSCODE_KUBERNETES_IMAGE_KEY
: debug.activeDebugSession
? DEBUG_IMAGE_KEY
: appName.includes('Insiders')
? VSCODE_INSIDERS_IMAGE_KEY
: VSCODE_IMAGE_KEY;

const defaultSmallImageText = config[CONFIG_KEYS.SmallImage].replace(REPLACE_KEYS.AppName, appName);
const defaultLargeImageText = config[CONFIG_KEYS.LargeImageIdling];
const removeDetails = config[CONFIG_KEYS.RemoveDetails];
Expand All @@ -184,8 +190,7 @@ export async function activity(previous: ActivityPayload = {}) {
smallImageKey: defaultSmallImageKey,
smallImageText: defaultSmallImageText,
};



if (swapBigAndSmallImage) {
state = {
...state,
Expand All @@ -195,10 +200,10 @@ export async function activity(previous: ActivityPayload = {}) {
smallImageText: defaultLargeImageText,
};
}

if (!removeRemoteRepository && git?.repositories.length) {
let repo = git.repositories.find((repo) => repo.ui.selected)?.state.remotes[0]?.fetchUrl;

if (repo) {
if (repo.startsWith('git@') || repo.startsWith('ssh://')) {
repo = repo.replace('ssh://', '').replace(':', '/').replace('git@', 'https://').replace('.git', '');
Expand Down
3 changes: 2 additions & 1 deletion src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import LANG from './data/languages.json';

export const CLIENT_ID = '1127365366977396867' as const;

export const KNOWN_EXTENSIONS: { [key: string]: { image: string, isRegular?: boolean } } = LANG.KNOWN_EXTENSIONS;
export const KNOWN_EXTENSIONS: { [key: string]: { image: string; isRegular?: boolean } } = LANG.KNOWN_EXTENSIONS;
export const KNOWN_LANGUAGES: { language: string; image: string }[] = LANG.KNOWN_LANGUAGES;

export const EMPTY = '' as const;
Expand All @@ -13,6 +13,7 @@ export const IDLE_IMAGE_KEY = 'vscode-big' as const;
export const DEBUG_IMAGE_KEY = 'debug' as const;
export const VSCODE_IMAGE_KEY = 'vscode' as const;
export const VSCODE_INSIDERS_IMAGE_KEY = 'vscode-insiders' as const;
export const VSCODE_KUBERNETES_IMAGE_KEY = 'kubernetes-dark' as const;

export const UNKNOWN_GIT_BRANCH = 'Unknown' as const;
export const UNKNOWN_GIT_REPO_NAME = 'Unknown' as const;
Expand Down
278 changes: 139 additions & 139 deletions src/extension.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
/* eslint-disable @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access */

import { Client } from 'discord-rpc';
import throttle from 'lodash-es/throttle';
import { commands, ExtensionContext, StatusBarAlignment, StatusBarItem, window, workspace, debug } from 'vscode';
import { Client } from 'discord-rpc';

import { activity } from './activity';
import { CLIENT_ID, CONFIG_KEYS } from './constants';
Expand All @@ -20,154 +20,154 @@ let idle: NodeJS.Timeout | undefined;
const listeners: { dispose: () => void }[] = [];

export function cleanUp() {
listeners.forEach((listener) => listener.dispose());
listeners.length = 0;
listeners.forEach((listener) => listener.dispose());
listeners.length = 0;
}

async function sendActivity() {
state = {
...(await activity(state)),
};
rpc.setActivity(state);
state = {
...(await activity(state)),
};
rpc.setActivity(state);
}

async function login() {
log(LogLevel.Info, 'Creating discord-rpc client');
rpc = new Client({ transport: 'ipc' });

rpc.on('ready', () => {
log(LogLevel.Info, 'Successfully connected to Discord');
cleanUp();

statusBarIcon.text = '$(globe) Connected to Discord';
statusBarIcon.tooltip = 'Connected to Discord';

void sendActivity();
const onChangeActiveTextEditor = window.onDidChangeActiveTextEditor(() => sendActivity());
const onChangeTextDocument = workspace.onDidChangeTextDocument(throttle(() => sendActivity(), 2000));
const onStartDebugSession = debug.onDidStartDebugSession(() => sendActivity());
const onTerminateDebugSession = debug.onDidTerminateDebugSession(() => sendActivity());

listeners.push(onChangeActiveTextEditor, onChangeTextDocument, onStartDebugSession, onTerminateDebugSession);
});

rpc.on('disconnected', () => {
cleanUp();
rpc.destroy();
statusBarIcon.text = '$(pulse) Reconnect to Discord';
statusBarIcon.command = 'discord.reconnect';
});

try {
await rpc.login({ clientId: CLIENT_ID });
} catch (error: any) {
log(LogLevel.Error, `Encountered the following error while trying to login:\n${error as string}`);
cleanUp();
rpc.destroy();
if (!config[CONFIG_KEYS.SuppressNotifications]) {
if (error?.message?.includes('ENOENT')) {
void window.showErrorMessage('No Discord client detected');
} else {
void window.showErrorMessage(`Couldn't connect to Discord via RPC: ${error as string}`);
}
}
statusBarIcon.text = '$(pulse) Reconnect to Discord';
statusBarIcon.command = 'discord.reconnect';
}
log(LogLevel.Info, 'Creating discord-rpc client');
rpc = new Client({ transport: 'ipc' });

rpc.on('ready', () => {
log(LogLevel.Info, 'Successfully connected to Discord');
cleanUp();

statusBarIcon.text = '$(globe) Connected to Discord';
statusBarIcon.tooltip = 'Connected to Discord';

void sendActivity();
const onChangeActiveTextEditor = window.onDidChangeActiveTextEditor(() => sendActivity());
const onChangeTextDocument = workspace.onDidChangeTextDocument(throttle(() => sendActivity(), 2000));
const onStartDebugSession = debug.onDidStartDebugSession(() => sendActivity());
const onTerminateDebugSession = debug.onDidTerminateDebugSession(() => sendActivity());

listeners.push(onChangeActiveTextEditor, onChangeTextDocument, onStartDebugSession, onTerminateDebugSession);
});

rpc.on('disconnected', () => {
cleanUp();
rpc.destroy();
statusBarIcon.text = '$(pulse) Reconnect to Discord';
statusBarIcon.command = 'discord.reconnect';
});

try {
await rpc.login({ clientId: CLIENT_ID });
} catch (error: any) {
log(LogLevel.Error, `Encountered the following error while trying to login:\n${error as string}`);
cleanUp();
rpc.destroy();
if (!config[CONFIG_KEYS.SuppressNotifications]) {
if (error?.message?.includes('ENOENT')) {
void window.showErrorMessage('No Discord client detected');
} else {
void window.showErrorMessage(`Couldn't connect to Discord via RPC: ${error as string}`);
}
}
statusBarIcon.text = '$(pulse) Reconnect to Discord';
statusBarIcon.command = 'discord.reconnect';
}
}

export async function activate(context: ExtensionContext) {
log(LogLevel.Info, 'Discord Presence activated');

let isWorkspaceExcluded = false;
for (const pattern of config[CONFIG_KEYS.WorkspaceExcludePatterns]) {
const regex = new RegExp(pattern);
const folders = workspace.workspaceFolders;
if (!folders) break;
if (folders.some((folder) => regex.test(folder.uri.fsPath))) {
isWorkspaceExcluded = true;
break;
}
}

const enable = async (update = true) => {
if (update) {
try {
await config.update('enabled', true);
} catch {}
}
log(LogLevel.Info, 'Enable: Cleaning up old listeners');
cleanUp();
statusBarIcon.text = '$(pulse) Connecting to Discord...';
statusBarIcon.show();
log(LogLevel.Info, 'Enable: Attempting to recreate login');
await login();
};

const disable = async (update = true) => {
if (update) {
try {
await config.update('enabled', false);
} catch {}
}
log(LogLevel.Info, 'Disable: Cleaning up old listeners');
cleanUp();
rpc?.destroy();
log(LogLevel.Info, 'Disable: Destroyed the rpc instance');
statusBarIcon.hide();
};

const enabler = commands.registerCommand('discord.enable', async () => {
await disable();
await enable();
await window.showInformationMessage('Enabled Discord Presence for this workspace');
});

const disabler = commands.registerCommand('discord.disable', async () => {
await disable();
await window.showInformationMessage('Disabled Discord Presence for this workspace');
});

const reconnecter = commands.registerCommand('discord.reconnect', async () => {
await disable(false);
await enable(false);
});

const disconnect = commands.registerCommand('discord.disconnect', async () => {
await disable(false);
statusBarIcon.text = '$(pulse) Reconnect to Discord';
statusBarIcon.command = 'discord.reconnect';
statusBarIcon.show();
});

context.subscriptions.push(enabler, disabler, reconnecter, disconnect);

if (!isWorkspaceExcluded && config[CONFIG_KEYS.Enabled]) {
statusBarIcon.show();
await login();
}

window.onDidChangeWindowState(async (windowState) => {
if (config[CONFIG_KEYS.IdleTimeout] !== 0) {
if (windowState.focused) {
if (idle) {
clearTimeout(idle);
}

await sendActivity();
} else {
idle = setTimeout(async () => {
state = {};
await rpc.clearActivity();
}, config[CONFIG_KEYS.IdleTimeout] * 1000);
}
}
});

await getGit();
log(LogLevel.Info, 'Discord Presence activated');

let isWorkspaceExcluded = false;
for (const pattern of config[CONFIG_KEYS.WorkspaceExcludePatterns]) {
const regex = new RegExp(pattern);
const folders = workspace.workspaceFolders;
if (!folders) break;
if (folders.some((folder) => regex.test(folder.uri.fsPath))) {
isWorkspaceExcluded = true;
break;
}
}

const enable = async (update = true) => {
if (update) {
try {
await config.update('enabled', true);
} catch {}
}
log(LogLevel.Info, 'Enable: Cleaning up old listeners');
cleanUp();
statusBarIcon.text = '$(pulse) Connecting to Discord...';
statusBarIcon.show();
log(LogLevel.Info, 'Enable: Attempting to recreate login');
await login();
};

const disable = async (update = true) => {
if (update) {
try {
await config.update('enabled', false);
} catch {}
}
log(LogLevel.Info, 'Disable: Cleaning up old listeners');
cleanUp();
rpc.destroy();
log(LogLevel.Info, 'Disable: Destroyed the rpc instance');
statusBarIcon.hide();
};

const enabler = commands.registerCommand('discord.enable', async () => {
await disable();
await enable();
await window.showInformationMessage('Enabled Discord Presence for this workspace');
});

const disabler = commands.registerCommand('discord.disable', async () => {
await disable();
await window.showInformationMessage('Disabled Discord Presence for this workspace');
});

const reconnecter = commands.registerCommand('discord.reconnect', async () => {
await disable(false);
await enable(false);
});

const disconnect = commands.registerCommand('discord.disconnect', async () => {
await disable(false);
statusBarIcon.text = '$(pulse) Reconnect to Discord';
statusBarIcon.command = 'discord.reconnect';
statusBarIcon.show();
});

context.subscriptions.push(enabler, disabler, reconnecter, disconnect);

if (!isWorkspaceExcluded && config[CONFIG_KEYS.Enabled]) {
statusBarIcon.show();
await login();
}

window.onDidChangeWindowState(async (windowState) => {
if (config[CONFIG_KEYS.IdleTimeout] !== 0) {
if (windowState.focused) {
if (idle) {
clearTimeout(idle);
}

await sendActivity();
} else {
idle = setTimeout(async () => {
state = {};
await rpc.clearActivity();
}, config[CONFIG_KEYS.IdleTimeout] * 1000);
}
}
});

await getGit();
}

export function deactivate() {
cleanUp();
rpc.destroy();
cleanUp();
rpc.destroy();
}
Loading

0 comments on commit 1292e4b

Please sign in to comment.