Skip to content

Commit

Permalink
Add apiUrl vscode settings json
Browse files Browse the repository at this point in the history
  • Loading branch information
alanhamlett committed Nov 15, 2024
1 parent 1c694cb commit b32a02c
Show file tree
Hide file tree
Showing 3 changed files with 72 additions and 70 deletions.
7 changes: 6 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,11 @@
"type": "string",
"description": "Defaults to value from ~/.wakatime.cfg, unless running in browser.",
"scope": "application"
},
"wakatime.apiUrl": {
"type": "string",
"description": "Defaults to https://api.wakatime.com/api/v1.",
"scope": "application"
}
}
}
Expand Down Expand Up @@ -146,4 +151,4 @@
"webpack-cli": "^4.9.2",
"which": "^2.0.2"
}
}
}
49 changes: 24 additions & 25 deletions src/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ export class Options {
return this.logFile;
}

public async getApiKeyAsync(): Promise<string> {
public async getApiKey(): Promise<string> {
if (!Utils.apiKeyInvalid(this.cache.api_key)) {
return this.cache.api_key;
}
Expand Down Expand Up @@ -233,6 +233,11 @@ export class Options {
return apiKey;
} catch (err) {
this.logger.debug(`Exception while reading API Key from config file: ${err}`);
if (`${err}`.includes('spawn EPERM')) {
vscode.window.showErrorMessage(
'Microsoft Defender is blocking WakaTime. Please allow WakaTime to run so it can upload code stats to your dashboard.',
);
}
return '';
}
}
Expand Down Expand Up @@ -275,30 +280,14 @@ export class Options {
}
}

public getApiKey(callback: (apiKey: string | null) => void): void {
this.getApiKeyAsync()
.then((apiKey) => {
if (!Utils.apiKeyInvalid(apiKey)) {
callback(apiKey);
} else {
callback(null);
}
})
.catch((err) => {
this.logger.warn(`Unable to get api key: ${err}`);
if (`${err}`.includes('spawn EPERM')) {
vscode.window.showErrorMessage(
'Microsoft Defender is blocking WakaTime. Please allow WakaTime to run so it can upload code stats to your dashboard.',
);
}
callback(null);
});
}

private getApiKeyFromEditor(): string {
return vscode.workspace.getConfiguration().get('wakatime.apiKey') || '';
}

private getApiUrlFromEditor(): string {
return vscode.workspace.getConfiguration().get('wakatime.apiUrl') || '';
}

// Support for gitpod.io https://github.com/wakatime/vscode-wakatime/pull/220
public getApiKeyFromEnv(): string {
if (this.cache.api_key_from_env !== undefined) return this.cache.api_key_from_env;
Expand All @@ -308,15 +297,25 @@ export class Options {
return this.cache.api_key_from_env;
}

public async getApiUrl(): Promise<string> {
let apiUrl = this.getApiUrlFromEnv();
public async getApiUrl(checkSettingsFile = false): Promise<string> {
let apiUrl = this.getApiUrlFromEditor();

if (!apiUrl) {
apiUrl = this.getApiUrlFromEnv();
}

if (!apiUrl && !checkSettingsFile) {
return '';
}

if (!apiUrl) {
try {
apiUrl = await this.getSettingAsync<string>('settings', 'api_url');
} catch (err) {
this.logger.debug(`Exception while reading API Url from config file: ${err}`);
}
}

if (!apiUrl) apiUrl = 'https://api.wakatime.com/api/v1';

const suffixes = ['/', '.bulk', '/users/current/heartbeats', '/heartbeats', '/heartbeat'];
Expand All @@ -329,7 +328,7 @@ export class Options {
return apiUrl;
}

public getApiUrlFromEnv(): string {
private getApiUrlFromEnv(): string {
if (this.cache.api_url_from_env !== undefined) return this.cache.api_url_from_env;

this.cache.api_url_from_env = process.env.WAKATIME_API_URL || '';
Expand All @@ -338,7 +337,7 @@ export class Options {
}

public hasApiKey(callback: (valid: boolean) => void): void {
this.getApiKeyAsync()
this.getApiKey()
.then((apiKey) => callback(!Utils.apiKeyInvalid(apiKey)))
.catch((err) => {
this.logger.warn(`Unable to check for api key: ${err}`);
Expand Down
86 changes: 42 additions & 44 deletions src/wakatime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -226,30 +226,29 @@ export class WakaTime {
this.statusBarTeamOther.tooltip = tooltipText;
}

public promptForApiKey(hidden: boolean = true): void {
this.options.getApiKey((defaultVal: string | null) => {
if (Utils.apiKeyInvalid(defaultVal ?? undefined)) defaultVal = '';
let promptOptions = {
prompt: 'WakaTime Api Key',
placeHolder: 'Enter your api key from https://wakatime.com/api-key',
value: defaultVal!,
ignoreFocusOut: true,
password: hidden,
validateInput: Utils.apiKeyInvalid.bind(this),
};
vscode.window.showInputBox(promptOptions).then((val) => {
if (val != undefined) {
let invalid = Utils.apiKeyInvalid(val);
if (!invalid) {
this.options.setSetting('settings', 'api_key', val, false);
} else vscode.window.setStatusBarMessage(invalid);
} else vscode.window.setStatusBarMessage('WakaTime api key not provided');
});
public async promptForApiKey(hidden: boolean = true): Promise<void> {
let defaultVal = await this.options.getApiKey();
if (Utils.apiKeyInvalid(defaultVal ?? undefined)) defaultVal = '';
let promptOptions = {
prompt: 'WakaTime Api Key',
placeHolder: 'Enter your api key from https://wakatime.com/api-key',
value: defaultVal!,
ignoreFocusOut: true,
password: hidden,
validateInput: Utils.apiKeyInvalid.bind(this),
};
vscode.window.showInputBox(promptOptions).then((val) => {
if (val != undefined) {
let invalid = Utils.apiKeyInvalid(val);
if (!invalid) {
this.options.setSetting('settings', 'api_key', val, false);
} else vscode.window.setStatusBarMessage(invalid);
} else vscode.window.setStatusBarMessage('WakaTime api key not provided');
});
}

public async promptForApiUrl(): Promise<void> {
const apiUrl = await this.options.getApiUrl();
const apiUrl = await this.options.getApiUrl(true);
let promptOptions = {
prompt: 'WakaTime Api Url (Defaults to https://api.wakatime.com/api/v1)',
placeHolder: 'https://api.wakatime.com/api/v1',
Expand Down Expand Up @@ -379,7 +378,7 @@ export class WakaTime {
}

public async openDashboardWebsite(): Promise<void> {
const url = (await this.options.getApiUrl()).replace('/api/v1', '').replace('api.', '');
const url = (await this.options.getApiUrl(true)).replace('/api/v1', '').replace('api.', '');
vscode.env.openExternal(vscode.Uri.parse(url));
}

Expand Down Expand Up @@ -519,31 +518,30 @@ export class WakaTime {
}, this.debounceMs);
}

private sendHeartbeat(
private async sendHeartbeat(
doc: vscode.TextDocument,
time: number,
selection: vscode.Position,
isWrite: boolean,
isCompiling: boolean,
isDebugging: boolean,
): void {
this.options.getApiKey((apiKey) => {
if (apiKey) {
this._sendHeartbeat(doc, time, selection, isWrite, isCompiling, isDebugging);
} else {
this.promptForApiKey();
}
});
): Promise<void> {
const apiKey = await this.options.getApiKey();
if (apiKey) {
await this._sendHeartbeat(doc, time, selection, isWrite, isCompiling, isDebugging);
} else {
await this.promptForApiKey();
}
}

private _sendHeartbeat(
private async _sendHeartbeat(
doc: vscode.TextDocument,
time: number,
selection: vscode.Position,
isWrite: boolean,
isCompiling: boolean,
isDebugging: boolean,
): void {
): Promise<void> {
if (!this.dependencies.isCliInstalled()) return;

let file = doc.fileName;
Expand Down Expand Up @@ -580,7 +578,7 @@ export class WakaTime {
const apiKey = this.options.getApiKeyFromEnv();
if (!Utils.apiKeyInvalid(apiKey)) args.push('--key', Utils.quote(apiKey));

const apiUrl = this.options.getApiUrlFromEnv();
const apiUrl = await this.options.getApiUrl();
if (apiUrl) args.push('--api-url', Utils.quote(apiUrl));

const project = this.getProjectName(doc.uri);
Expand Down Expand Up @@ -612,7 +610,7 @@ export class WakaTime {
this.logger.error(error.toString());
}
});
proc.on('close', (code, _signal) => {
proc.on('close', async (code, _signal) => {
if (code == 0) {
if (this.showStatusBar) this.getCodingActivity();
} else if (code == 102 || code == 112) {
Expand Down Expand Up @@ -642,7 +640,7 @@ export class WakaTime {
let now: number = Date.now();
if (this.lastApiKeyPrompted < now - 86400000) {
// only prompt once per day
this.promptForApiKey(false);
await this.promptForApiKey(false);
this.lastApiKeyPrompted = now;
}
} else {
Expand All @@ -656,21 +654,21 @@ export class WakaTime {
});
}

private getCodingActivity() {
private async getCodingActivity() {
if (!this.showStatusBar) return;

const cutoff = Date.now() - this.fetchTodayInterval;
if (this.lastFetchToday > cutoff) return;

this.lastFetchToday = Date.now();

this.options.getApiKey((apiKey) => {
if (!apiKey) return;
this._getCodingActivity();
});
const apiKey = await this.options.getApiKey();
if (!apiKey) return;

await this._getCodingActivity();
}

private _getCodingActivity() {
private async _getCodingActivity() {
if (!this.dependencies.isCliInstalled()) return;

let user_agent =
Expand All @@ -682,7 +680,7 @@ export class WakaTime {
const apiKey = this.options.getApiKeyFromEnv();
if (!Utils.apiKeyInvalid(apiKey)) args.push('--key', Utils.quote(apiKey));

const apiUrl = this.options.getApiUrlFromEnv();
const apiUrl = await this.options.getApiUrl();
if (apiUrl) args.push('--api-url', Utils.quote(apiUrl));

if (Desktop.isWindows()) {
Expand Down Expand Up @@ -764,7 +762,7 @@ export class WakaTime {
}
}

private updateTeamStatusBar(doc?: vscode.TextDocument) {
private async updateTeamStatusBar(doc?: vscode.TextDocument) {
if (!this.showStatusBarTeam) return;
if (!this.hasTeamFeatures) return;
if (!this.dependencies.isCliInstalled()) return;
Expand Down Expand Up @@ -802,7 +800,7 @@ export class WakaTime {
const apiKey = this.options.getApiKeyFromEnv();
if (!Utils.apiKeyInvalid(apiKey)) args.push('--key', Utils.quote(apiKey));

const apiUrl = this.options.getApiUrlFromEnv();
const apiUrl = await this.options.getApiUrl();
if (apiUrl) args.push('--api-url', Utils.quote(apiUrl));

const project = this.getProjectName(doc.uri);
Expand Down

0 comments on commit b32a02c

Please sign in to comment.