Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: configure base url #179

Merged
merged 4 commits into from
Mar 28, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions src/components/Options.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ interface State {
alertText: string;
alertType: SuccessOrFailType;
apiKey: string;
apiUrl: string;
blacklist: string;
displayAlert: boolean;
hostname: string;
Expand All @@ -25,6 +26,7 @@ export default function Options(): JSX.Element {
alertText: config.alert.success.text,
alertType: config.alert.success.type,
apiKey: '',
apiUrl: config.apiUrl,
blacklist: '',
displayAlert: false,
hostname: '',
Expand All @@ -42,6 +44,7 @@ export default function Options(): JSX.Element {
const restoreSettings = async (): Promise<void> => {
const items = await browser.storage.sync.get({
apiKey: config.apiKey,
apiUrl: config.apiUrl,
blacklist: '',
hostname: config.hostname,
loggingStyle: config.loggingStyle,
Expand All @@ -54,6 +57,7 @@ export default function Options(): JSX.Element {
setState({
...state,
apiKey: items.apiKey as string,
apiUrl: items.apiUrl as string,
blacklist: items.blacklist as string,
hostname: items.hostname as string,
loggingStyle: items.loggingStyle as string,
Expand Down Expand Up @@ -82,6 +86,7 @@ export default function Options(): JSX.Element {
setState({ ...state, loading: true });

const apiKey = state.apiKey;
const apiUrl = state.apiUrl;
const theme = state.theme;
const hostname = state.hostname;
const loggingType = state.loggingType;
Expand All @@ -95,6 +100,7 @@ export default function Options(): JSX.Element {
// Sync options with google storage.
await browser.storage.sync.set({
apiKey,
apiUrl,
blacklist,
hostname,
loggingStyle,
Expand All @@ -109,6 +115,7 @@ export default function Options(): JSX.Element {
setState({
...state,
apiKey,
apiUrl,
blacklist,
displayAlert: true,
hostname,
Expand Down Expand Up @@ -273,6 +280,23 @@ export default function Options(): JSX.Element {
</div>
</div>

<div className="form-group">
<label htmlFor="theme" className="col-lg-2 control-label">
API Url
</label>

<div className="col-lg-10">
<input
type="text"
className="form-control"
value={state.apiUrl}
onChange={(e) => setState({ ...state, apiUrl: e.target.value })}
placeholder="https://wakatime.com/api/v1"
/>
<span className="help-block">https://wakatime.com/api/v1</span>
</div>
</div>

<div className="form-group row">
<div className="col-lg-10 col-lg-offset-2 space-between align-items-center">
<div
Expand Down
10 changes: 5 additions & 5 deletions src/components/WakaTime.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import React, { useEffect, useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { useDispatch, useSelector } from 'react-redux';
import config from '../config/config';
import { ApiKeyReducer, ReduxSelector } from '../types/store';
import { fetchUserData } from '../utils/user';
import apiKeyInvalid from '../utils/apiKey';
import config from '../config/config';
import { fetchUserData } from '../utils/user';
import Alert from './Alert';
import NavBar from './NavBar';
import MainList from './MainList';
import NavBar from './NavBar';

export default function WakaTime(): JSX.Element {
const dispatch = useDispatch();
Expand Down Expand Up @@ -35,7 +35,7 @@ export default function WakaTime(): JSX.Element {
{isApiKeyValid && extensionState === 'notSignedIn' && (
<Alert
type={config.alert.failure.type}
text={'Invalid api key'}
text={'Invalid API key or API url'}
onClick={() => browser.runtime.openOptionsPage()}
style={{ cursor: 'pointer' }}
/>
Expand Down
7 changes: 4 additions & 3 deletions src/config/config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,14 @@ describe('wakatime config', () => {
},
},
"apiKey": "",
"apiUrl": "https://wakatime.com/api/v1",
"colors": {
"allGood": "",
"lightTheme": "white",
"notLogging": "gray",
"notSignedIn": "red",
},
"currentUserApiUrl": "https://wakatime.com/api/v1/users/current",
"currentUserApiEndPoint": "/users/current",
"detectionIntervalInSeconds": 60,
"devSites": "https://codepen.io/
https://www.codewars.com/
Expand All @@ -43,7 +44,7 @@ describe('wakatime config', () => {
https://stackoverflow.com/
https://www.udemy.com/
https://www.w3schools.com/",
"heartbeatApiUrl": "https://wakatime.com/api/v1/users/current/heartbeats",
"heartbeatApiEndPoint": "/users/current/heartbeats",
"hostname": "",
"loggingEnabled": true,
"loggingStyle": "blacklist",
Expand All @@ -67,7 +68,7 @@ describe('wakatime config', () => {
"blacklisted",
"whitelisted",
],
"summariesApiUrl": "https://wakatime.com/api/v1/users/current/summaries",
"summariesApiEndPoint": "/users/current/summaries",
"theme": "light",
"tooltips": {
"allGood": "",
Expand Down
18 changes: 9 additions & 9 deletions src/config/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,11 +53,12 @@ export interface Config {
* API key use to query wakatime api
*/
apiKey: '';
apiUrl: string;
colors: Colors;
/**
* Url from which to detect if the user is logged in
*/
currentUserApiUrl: string;
currentUserApiEndPoint: string;
/**
* Time for idle state of the browser
* The user is considered idle if there was
Expand All @@ -69,7 +70,7 @@ export interface Config {
/**
* Url to which to send the heartbeat
*/
heartbeatApiUrl: string;
heartbeatApiEndPoint: string;

hostname: string;
/**
Expand All @@ -91,7 +92,7 @@ export interface Config {
/**
* Get stats from the wakatime api
*/
summariesApiUrl: string;
summariesApiEndPoint: string;
/**
* Options for theme
*/
Expand All @@ -118,23 +119,23 @@ const config: Config = {

apiKey: '',

apiUrl: process.env.API_URL ?? 'https://wakatime.com/api/v1',

colors: {
allGood: '',
lightTheme: 'white',
notLogging: 'gray',
notSignedIn: 'red',
},

currentUserApiUrl:
process.env.CURRENT_USER_API_URL ?? 'https://wakatime.com/api/v1/users/current',
currentUserApiEndPoint: process.env.CURRENT_USER_API_URL ?? '/users/current',

detectionIntervalInSeconds: 60,

devSites:
'https://codepen.io/\nhttps://www.codewars.com/\nhttps://dev.to/\nhttps://github.com/\nhttps://www.hackerrank.com/\nhttps://leetcode.com/\nhttps://developer.mozilla.org/en-US/\nhttps://stackoverflow.com/\nhttps://www.udemy.com/\nhttps://www.w3schools.com/',

heartbeatApiUrl:
process.env.HEART_BEAT_API_URL ?? 'https://wakatime.com/api/v1/users/current/heartbeats',
heartbeatApiEndPoint: process.env.HEARTBEAT_API_URL ?? '/users/current/heartbeats',

hostname: '',

Expand All @@ -152,8 +153,7 @@ const config: Config = {

states: ['allGood', 'notLogging', 'notSignedIn', 'blacklisted', 'whitelisted'],

summariesApiUrl:
process.env.SUMMARIES_API_URL ?? 'https://wakatime.com/api/v1/users/current/summaries',
summariesApiEndPoint: process.env.SUMMARIES_API_URL ?? '/users/current/summaries',

theme: 'light',

Expand Down
30 changes: 26 additions & 4 deletions src/core/WakaTimeCore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,14 @@ class WakaTimeCore {
}

async getTotalTimeLoggedToday(api_key = ''): Promise<GrandTotal> {
const items = await browser.storage.sync.get({
apiUrl: config.apiUrl,
summariesApiEndPoint: config.summariesApiEndPoint,
});

const today = moment().format('YYYY-MM-DD');
const summariesAxiosPayload: AxiosResponse<SummariesPayload> = await axios.get(
config.summariesApiUrl,
`${items.apiUrl}${items.summariesApiEndPoint}`,
{
params: {
api_key,
Expand All @@ -70,8 +75,13 @@ class WakaTimeCore {
*/
async fetchApiKey(): Promise<string> {
try {
const items = await browser.storage.sync.get({
apiUrl: config.apiUrl,
currentUserApiEndPoint: config.currentUserApiEndPoint,
});

const apiKeyResponse: AxiosResponse<ApiKeyPayload> = await axios.post(
`${config.currentUserApiUrl}/get_api_key`,
`${items.apiUrl}${items.currentUserApiEndPoint}/get_api_key`,
);
return apiKeyResponse.data.data.api_key;
} catch (err: unknown) {
Expand All @@ -85,8 +95,12 @@ class WakaTimeCore {
* @returns {*}
*/
async checkAuth(api_key = ''): Promise<User> {
const items = await browser.storage.sync.get({
apiUrl: config.apiUrl,
currentUserApiEndPoint: config.currentUserApiEndPoint,
});
const userPayload: AxiosResponse<AxiosUserResponse> = await axios.get(
config.currentUserApiUrl,
`${items.apiUrl}${items.currentUserApiEndPoint}`,
{ params: { api_key } },
);
return userPayload.data.data;
Expand Down Expand Up @@ -345,6 +359,11 @@ class WakaTimeCore {
hostname = '',
): Promise<void> {
try {
const items = await browser.storage.sync.get({
apiUrl: config.apiUrl,
heartbeatApiEndPoint: config.heartbeatApiEndPoint,
});

const request: RequestInit = {
body: JSON.stringify(payload),
credentials: 'omit',
Expand All @@ -355,7 +374,10 @@ class WakaTimeCore {
'X-Machine-Name': hostname,
};
}
const response = await fetch(`${config.heartbeatApiUrl}?api_key=${apiKey}`, request);
const response = await fetch(
`${items.apiUrl}${items.heartbeatApiEndPoint}?api_key=${apiKey}`,
request,
);
await response.json();
} catch (err: unknown) {
if (this.db) {
Expand Down
2 changes: 1 addition & 1 deletion src/manifests/chrome.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,5 +26,5 @@
"page": "options.html"
},
"permissions": ["alarms", "tabs", "storage", "idle"],
"version": "3.0.7"
"version": "3.0.8"
}
2 changes: 1 addition & 1 deletion src/manifests/firefox.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,5 +39,5 @@
"storage",
"idle"
],
"version": "3.0.7"
"version": "3.0.8"
}
16 changes: 12 additions & 4 deletions src/reducers/currentUser.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
import axios, { AxiosResponse } from 'axios';
import { CurrentUser, User, UserPayload } from '../types/user';
import browser from 'webextension-polyfill';
import config from '../config/config';
import { CurrentUser, User, UserPayload } from '../types/user';

interface setUserAction {
payload: User | undefined;
Expand All @@ -14,9 +15,16 @@ export const name: NameType = 'currentUser';
export const fetchCurrentUser = createAsyncThunk<User, string>(
`[${name}]`,
async (api_key = '') => {
const userPayload: AxiosResponse<UserPayload> = await axios.get(config.currentUserApiUrl, {
params: { api_key },
const items = await browser.storage.sync.get({
apiUrl: config.apiUrl,
currentUserApiEndPoint: config.currentUserApiEndPoint,
});
const userPayload: AxiosResponse<UserPayload> = await axios.get(
`${items.apiUrl}${items.currentUserApiEndPoint}`,
{
params: { api_key },
},
);
return userPayload.data.data;
},
);
Expand Down
13 changes: 4 additions & 9 deletions webpack.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,17 +55,12 @@ const getConfigByBrowser = (isProd: boolean, browser: BrowserTypes): webpack.Con
],
}),
new webpack.DefinePlugin({
['process.env.CURRENT_USER_API_URL']: JSON.stringify(
'https://wakatime.com/api/v1/users/current',
),
['process.env.HEART_BEAT_API_URL']: JSON.stringify(
'https://wakatime.com/api/v1/users/current/heartbeats',
),
['process.env.API_URL']: JSON.stringify('https://wakatime.com/api/v1'),
['process.env.CURRENT_USER_API_URL']: JSON.stringify('/users/current'),
['process.env.HEARTBEAT_API_URL']: JSON.stringify('/users/current/heartbeats'),
['process.env.LOGOUT_USER_URL']: JSON.stringify('https://wakatime.com/logout'),
['process.env.NODE_ENV']: JSON.stringify(isProd ? 'production' : 'development'),
['process.env.SUMMARIES_API_URL']: JSON.stringify(
'https://wakatime.com/api/v1/users/current/summaries',
),
['process.env.SUMMARIES_API_URL']: JSON.stringify('/users/current/summaries'),
}),
],
resolve: {
Expand Down