start refactor
This commit is contained in:
@@ -2,31 +2,24 @@ import React, { useEffect, useRef, useState } from 'react';
|
|||||||
import config, { SuccessOrFailType } from '../config/config';
|
import config, { SuccessOrFailType } from '../config/config';
|
||||||
import { IS_CHROME } from '../utils';
|
import { IS_CHROME } from '../utils';
|
||||||
import apiKeyInvalid from '../utils/apiKey';
|
import apiKeyInvalid from '../utils/apiKey';
|
||||||
|
import { getSettings, saveSettings, Settings } from '../utils/settings';
|
||||||
import { logUserIn } from '../utils/user';
|
import { logUserIn } from '../utils/user';
|
||||||
import SitesList from './SitesList';
|
import SitesList from './SitesList';
|
||||||
|
|
||||||
interface State {
|
interface State extends Settings {
|
||||||
alertText: string;
|
alertText: string;
|
||||||
alertType: SuccessOrFailType;
|
alertType: SuccessOrFailType;
|
||||||
apiKey: string;
|
|
||||||
apiUrl: string;
|
|
||||||
blacklist: string;
|
|
||||||
hostname: string;
|
|
||||||
loading: boolean;
|
loading: boolean;
|
||||||
loggingStyle: string;
|
|
||||||
loggingType: string;
|
|
||||||
socialMediaSites: string[];
|
|
||||||
theme: string;
|
|
||||||
trackSocialMedia: boolean;
|
|
||||||
whitelist: string;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function Options(): JSX.Element {
|
export default function Options(): JSX.Element {
|
||||||
const [state, setState] = useState<State>({
|
const [state, setState] = useState<State>({
|
||||||
alertText: config.alert.success.text,
|
alertText: config.alert.success.text,
|
||||||
alertType: config.alert.success.type,
|
alertType: config.alert.success.type,
|
||||||
|
allowList: [],
|
||||||
apiKey: '',
|
apiKey: '',
|
||||||
apiUrl: config.apiUrl,
|
apiUrl: config.apiUrl,
|
||||||
blacklist: '',
|
denyList: [],
|
||||||
hostname: '',
|
hostname: '',
|
||||||
loading: false,
|
loading: false,
|
||||||
loggingStyle: config.loggingStyle,
|
loggingStyle: config.loggingStyle,
|
||||||
@@ -34,45 +27,15 @@ export default function Options(): JSX.Element {
|
|||||||
socialMediaSites: config.socialMediaSites,
|
socialMediaSites: config.socialMediaSites,
|
||||||
theme: config.theme,
|
theme: config.theme,
|
||||||
trackSocialMedia: config.trackSocialMedia,
|
trackSocialMedia: config.trackSocialMedia,
|
||||||
whitelist: '',
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const loggingStyleRef = useRef(null);
|
const loggingStyleRef = useRef(null);
|
||||||
|
|
||||||
const restoreSettings = async (): Promise<void> => {
|
const restoreSettings = async (): Promise<void> => {
|
||||||
const items = await browser.storage.sync.get({
|
const settings = await getSettings();
|
||||||
apiKey: config.apiKey,
|
|
||||||
apiUrl: config.apiUrl,
|
|
||||||
blacklist: '',
|
|
||||||
hostname: config.hostname,
|
|
||||||
loggingStyle: config.loggingStyle,
|
|
||||||
loggingType: config.loggingType,
|
|
||||||
socialMediaSites: config.socialMediaSites,
|
|
||||||
theme: config.theme,
|
|
||||||
trackSocialMedia: true,
|
|
||||||
whitelist: '',
|
|
||||||
});
|
|
||||||
|
|
||||||
// Handle prod accounts with old social media stored as string
|
|
||||||
if (typeof items.socialMediaSites === 'string') {
|
|
||||||
await browser.storage.sync.set({
|
|
||||||
socialMediaSites: items.socialMediaSites.split('\n'),
|
|
||||||
});
|
|
||||||
items.socialMediaSites = items.socialMediaSites.split('\n');
|
|
||||||
}
|
|
||||||
|
|
||||||
setState({
|
setState({
|
||||||
...state,
|
...state,
|
||||||
apiKey: items.apiKey as string,
|
...settings,
|
||||||
apiUrl: items.apiUrl as string,
|
|
||||||
blacklist: items.blacklist as string,
|
|
||||||
hostname: items.hostname as string,
|
|
||||||
loggingStyle: items.loggingStyle as string,
|
|
||||||
loggingType: items.loggingType as string,
|
|
||||||
socialMediaSites: items.socialMediaSites as string[],
|
|
||||||
theme: items.theme as string,
|
|
||||||
trackSocialMedia: items.trackSocialMedia as boolean,
|
|
||||||
whitelist: items.whitelist as string,
|
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -83,68 +46,60 @@ export default function Options(): JSX.Element {
|
|||||||
const handleSubmit = async () => {
|
const handleSubmit = async () => {
|
||||||
if (state.loading) return;
|
if (state.loading) return;
|
||||||
setState({ ...state, loading: true });
|
setState({ ...state, loading: true });
|
||||||
|
if (state.apiUrl.endsWith('/')) {
|
||||||
const apiKey = state.apiKey;
|
state.apiUrl = state.apiUrl.slice(0, -1);
|
||||||
const theme = state.theme;
|
|
||||||
const hostname = state.hostname;
|
|
||||||
const loggingType = state.loggingType;
|
|
||||||
const loggingStyle = state.loggingStyle;
|
|
||||||
const trackSocialMedia = state.trackSocialMedia;
|
|
||||||
const socialMediaSites = state.socialMediaSites;
|
|
||||||
// Trimming blacklist and whitelist removes blank lines and spaces.
|
|
||||||
const blacklist = state.blacklist.trim();
|
|
||||||
const whitelist = state.whitelist.trim();
|
|
||||||
let apiUrl = state.apiUrl;
|
|
||||||
|
|
||||||
if (apiUrl.endsWith('/')) {
|
|
||||||
apiUrl = apiUrl.slice(0, -1);
|
|
||||||
}
|
}
|
||||||
|
await saveSettings({
|
||||||
// Sync options with google storage.
|
allowList: state.allowList,
|
||||||
await browser.storage.sync.set({
|
apiKey: state.apiKey,
|
||||||
apiKey,
|
apiUrl: state.apiUrl,
|
||||||
apiUrl,
|
denyList: state.denyList,
|
||||||
blacklist,
|
hostname: state.hostname,
|
||||||
hostname,
|
loggingStyle: state.loggingStyle,
|
||||||
loggingStyle,
|
loggingType: state.loggingType,
|
||||||
loggingType,
|
socialMediaSites: state.socialMediaSites,
|
||||||
socialMediaSites,
|
theme: state.theme,
|
||||||
theme,
|
trackSocialMedia: state.trackSocialMedia,
|
||||||
trackSocialMedia,
|
|
||||||
whitelist,
|
|
||||||
});
|
|
||||||
|
|
||||||
// Set state to be newly entered values.
|
|
||||||
setState({
|
|
||||||
...state,
|
|
||||||
apiKey,
|
|
||||||
apiUrl,
|
|
||||||
blacklist,
|
|
||||||
hostname,
|
|
||||||
loggingStyle,
|
|
||||||
loggingType,
|
|
||||||
socialMediaSites,
|
|
||||||
theme,
|
|
||||||
trackSocialMedia,
|
|
||||||
whitelist,
|
|
||||||
});
|
});
|
||||||
|
setState(state);
|
||||||
await logUserIn(state.apiKey);
|
await logUserIn(state.apiKey);
|
||||||
if (IS_CHROME) {
|
if (IS_CHROME) {
|
||||||
window.close();
|
window.close();
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const updateBlacklistState = (sites: string) => {
|
const updateDenyListState = (sites: string) => {
|
||||||
setState({
|
setState({
|
||||||
...state,
|
...state,
|
||||||
blacklist: sites,
|
denyList: sites.trim().split('\n'),
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const updateWhitelistState = (sites: string) => {
|
const updateAllowListState = (sites: string) => {
|
||||||
setState({
|
setState({
|
||||||
...state,
|
...state,
|
||||||
whitelist: sites,
|
allowList: sites.trim().split('\n'),
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const updateLoggingStyle = (style: string) => {
|
||||||
|
setState({
|
||||||
|
...state,
|
||||||
|
loggingStyle: style === 'allow' ? 'allow' : 'deny',
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const updateLoggingType = (type: string) => {
|
||||||
|
setState({
|
||||||
|
...state,
|
||||||
|
loggingType: type === 'url' ? 'url' : 'domain',
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const updateTheme = (theme: string) => {
|
||||||
|
setState({
|
||||||
|
...state,
|
||||||
|
theme: theme === 'light' ? 'light' : 'dark',
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -153,24 +108,25 @@ export default function Options(): JSX.Element {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const loggingStyle = function () {
|
const loggingStyle = function () {
|
||||||
if (state.loggingStyle == 'blacklist') {
|
// TODO: rewrite SitesList to be structured inputs instead of textarea
|
||||||
|
|
||||||
|
if (state.loggingStyle == 'deny') {
|
||||||
return (
|
return (
|
||||||
<SitesList
|
<SitesList
|
||||||
handleChange={updateBlacklistState}
|
handleChange={updateDenyListState}
|
||||||
label="Blacklist"
|
label="Exclude"
|
||||||
sites={state.blacklist}
|
sites={state.denyList.join('\n')}
|
||||||
helpText="Sites that you don't want to show in your reports."
|
helpText="Sites that you don't want to show in your reports."
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<SitesList
|
<SitesList
|
||||||
handleChange={updateWhitelistState}
|
handleChange={updateAllowListState}
|
||||||
label="Whitelist"
|
label="Include"
|
||||||
sites={state.whitelist}
|
sites={state.allowList.join('\n')}
|
||||||
placeholder="http://google.com http://myproject.com/MyProject"
|
placeholder="http://google.com http://myproject.com/MyProject"
|
||||||
helpText="Sites that you want to show in your reports. You can assign URL to project by adding @@YourProject at the end of line."
|
helpText="Only track these sites. You can assign URL to project by adding @@YourProject at the end of line."
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
@@ -206,10 +162,10 @@ export default function Options(): JSX.Element {
|
|||||||
ref={loggingStyleRef}
|
ref={loggingStyleRef}
|
||||||
className="form-control"
|
className="form-control"
|
||||||
value={state.loggingStyle}
|
value={state.loggingStyle}
|
||||||
onChange={(e) => setState({ ...state, loggingStyle: e.target.value })}
|
onChange={(e) => updateLoggingStyle(e.target.value)}
|
||||||
>
|
>
|
||||||
<option value="blacklist">All except blacklisted sites</option>
|
<option value="denyList">All except excluded sites</option>
|
||||||
<option value="whitelist">Only whitelisted sites</option>
|
<option value="allowList">Only allowed sites</option>
|
||||||
</select>
|
</select>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -223,7 +179,7 @@ export default function Options(): JSX.Element {
|
|||||||
id="loggingType"
|
id="loggingType"
|
||||||
className="form-control"
|
className="form-control"
|
||||||
value={state.loggingType}
|
value={state.loggingType}
|
||||||
onChange={(e) => setState({ ...state, loggingType: e.target.value })}
|
onChange={(e) => updateLoggingType(e.target.value)}
|
||||||
>
|
>
|
||||||
<option value="domain">Only the domain</option>
|
<option value="domain">Only the domain</option>
|
||||||
<option value="url">Entire URL</option>
|
<option value="url">Entire URL</option>
|
||||||
@@ -238,7 +194,7 @@ export default function Options(): JSX.Element {
|
|||||||
id="selectTheme"
|
id="selectTheme"
|
||||||
className="form-control"
|
className="form-control"
|
||||||
value={state.theme}
|
value={state.theme}
|
||||||
onChange={(e) => setState({ ...state, theme: e.target.value })}
|
onChange={(e) => updateTheme(e.target.value)}
|
||||||
>
|
>
|
||||||
<option value="light">Light</option>
|
<option value="light">Light</option>
|
||||||
<option value="dark">Dark</option>
|
<option value="dark">Dark</option>
|
||||||
|
|||||||
@@ -49,7 +49,7 @@ describe('wakatime config', () => {
|
|||||||
"heartbeatApiEndPoint": "/users/current/heartbeats",
|
"heartbeatApiEndPoint": "/users/current/heartbeats",
|
||||||
"hostname": "",
|
"hostname": "",
|
||||||
"loggingEnabled": true,
|
"loggingEnabled": true,
|
||||||
"loggingStyle": "blacklist",
|
"loggingStyle": "deny",
|
||||||
"loggingType": "domain",
|
"loggingType": "domain",
|
||||||
"logoutUserUrl": "https://wakatime.com/logout",
|
"logoutUserUrl": "https://wakatime.com/logout",
|
||||||
"name": "WakaTime",
|
"name": "WakaTime",
|
||||||
@@ -73,17 +73,15 @@ describe('wakatime config', () => {
|
|||||||
"allGood",
|
"allGood",
|
||||||
"notLogging",
|
"notLogging",
|
||||||
"notSignedIn",
|
"notSignedIn",
|
||||||
"blacklisted",
|
"ignored",
|
||||||
"whitelisted",
|
|
||||||
],
|
],
|
||||||
"summariesApiEndPoint": "/users/current/summaries",
|
"summariesApiEndPoint": "/users/current/summaries",
|
||||||
"theme": "light",
|
"theme": "light",
|
||||||
"tooltips": {
|
"tooltips": {
|
||||||
"allGood": "",
|
"allGood": "",
|
||||||
"blacklisted": "This URL is blacklisted",
|
"ignored": "This URL is ignored",
|
||||||
"notLogging": "Not logging",
|
"notLogging": "Not logging",
|
||||||
"notSignedIn": "Not signed In",
|
"notSignedIn": "Not signed In",
|
||||||
"whitelisted": "This URL is not on your whitelist",
|
|
||||||
},
|
},
|
||||||
"trackSocialMedia": true,
|
"trackSocialMedia": true,
|
||||||
"version": "test-version",
|
"version": "test-version",
|
||||||
|
|||||||
@@ -3,16 +3,18 @@ import browser from 'webextension-polyfill';
|
|||||||
/**
|
/**
|
||||||
* Logging
|
* Logging
|
||||||
*/
|
*/
|
||||||
export type ApiStates = 'allGood' | 'notLogging' | 'notSignedIn' | 'blacklisted' | 'whitelisted';
|
export type ApiStates = 'allGood' | 'notLogging' | 'notSignedIn' | 'ignored';
|
||||||
/**
|
/**
|
||||||
* Supported logging style
|
* Supported logging style
|
||||||
*/
|
*/
|
||||||
export type LoggingStyle = 'whitelist' | 'blacklist';
|
export type LoggingStyle = 'allow' | 'deny';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Logging type
|
* Logging type
|
||||||
*/
|
*/
|
||||||
export type LoggingType = 'domain' | 'url';
|
export type LoggingType = 'domain' | 'url';
|
||||||
export type SuccessOrFailType = 'success' | 'danger';
|
export type SuccessOrFailType = 'success' | 'danger';
|
||||||
|
export type Theme = 'light' | 'dark';
|
||||||
/**
|
/**
|
||||||
* Predefined alert type and text for success and failure.
|
* Predefined alert type and text for success and failure.
|
||||||
*/
|
*/
|
||||||
@@ -41,10 +43,9 @@ interface Colors {
|
|||||||
*/
|
*/
|
||||||
interface Tooltips {
|
interface Tooltips {
|
||||||
allGood: string;
|
allGood: string;
|
||||||
blacklisted: string;
|
ignored: string;
|
||||||
notLogging: string;
|
notLogging: string;
|
||||||
notSignedIn: string;
|
notSignedIn: string;
|
||||||
whitelisted: string;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Config {
|
export interface Config {
|
||||||
@@ -97,7 +98,7 @@ export interface Config {
|
|||||||
/**
|
/**
|
||||||
* Options for theme
|
* Options for theme
|
||||||
*/
|
*/
|
||||||
theme: 'light';
|
theme: Theme;
|
||||||
tooltips: Tooltips;
|
tooltips: Tooltips;
|
||||||
trackSocialMedia: boolean;
|
trackSocialMedia: boolean;
|
||||||
/**
|
/**
|
||||||
@@ -152,7 +153,7 @@ const config: Config = {
|
|||||||
|
|
||||||
loggingEnabled: true,
|
loggingEnabled: true,
|
||||||
|
|
||||||
loggingStyle: 'blacklist',
|
loggingStyle: 'deny',
|
||||||
|
|
||||||
loggingType: 'domain',
|
loggingType: 'domain',
|
||||||
|
|
||||||
@@ -175,7 +176,7 @@ const config: Config = {
|
|||||||
'youtube.com',
|
'youtube.com',
|
||||||
],
|
],
|
||||||
|
|
||||||
states: ['allGood', 'notLogging', 'notSignedIn', 'blacklisted', 'whitelisted'],
|
states: ['allGood', 'notLogging', 'notSignedIn', 'ignored'],
|
||||||
|
|
||||||
summariesApiEndPoint: process.env.SUMMARIES_API_URL ?? '/users/current/summaries',
|
summariesApiEndPoint: process.env.SUMMARIES_API_URL ?? '/users/current/summaries',
|
||||||
|
|
||||||
@@ -183,10 +184,9 @@ const config: Config = {
|
|||||||
|
|
||||||
tooltips: {
|
tooltips: {
|
||||||
allGood: '',
|
allGood: '',
|
||||||
blacklisted: 'This URL is blacklisted',
|
ignored: 'This URL is ignored',
|
||||||
notLogging: 'Not logging',
|
notLogging: 'Not logging',
|
||||||
notSignedIn: 'Not signed In',
|
notSignedIn: 'Not signed In',
|
||||||
whitelisted: 'This URL is not on your whitelist',
|
|
||||||
},
|
},
|
||||||
trackSocialMedia: true,
|
trackSocialMedia: true,
|
||||||
|
|
||||||
|
|||||||
@@ -1,21 +1,23 @@
|
|||||||
/* eslint-disable no-fallthrough */
|
|
||||||
/* eslint-disable default-case */
|
|
||||||
import axios, { AxiosResponse } from 'axios';
|
|
||||||
import { IDBPDatabase, openDB } from 'idb';
|
import { IDBPDatabase, openDB } from 'idb';
|
||||||
import moment from 'moment';
|
import moment from 'moment';
|
||||||
import browser, { Tabs } from 'webextension-polyfill';
|
import browser, { Tabs } from 'webextension-polyfill';
|
||||||
|
import { IS_EDGE, IS_FIREFOX, getOperatingSystem, isCodeReviewing } from '../utils';
|
||||||
|
import { getHeartbeatFromPage } from '../utils/heartbeat';
|
||||||
|
/* eslint-disable no-fallthrough */
|
||||||
|
/* eslint-disable default-case */
|
||||||
|
import getDomainFromUrl, { getDomain } from '../utils/getDomainFromUrl';
|
||||||
|
|
||||||
import config from '../config/config';
|
import config from '../config/config';
|
||||||
import { SendHeartbeat } from '../types/heartbeats';
|
import { Heartbeat } from '../types/heartbeats';
|
||||||
import { GrandTotal, SummariesPayload } from '../types/summaries';
|
|
||||||
import { ApiKeyPayload, AxiosUserResponse, User } from '../types/user';
|
|
||||||
import { IS_EDGE, IS_FIREFOX, generateProjectFromDevSites, isCodeReviewing } from '../utils';
|
|
||||||
import { getApiKey } from '../utils/apiKey';
|
import { getApiKey } from '../utils/apiKey';
|
||||||
import changeExtensionState from '../utils/changeExtensionState';
|
import changeExtensionState from '../utils/changeExtensionState';
|
||||||
import contains from '../utils/contains';
|
import contains from '../utils/contains';
|
||||||
import getDomainFromUrl, { getDomain } from '../utils/getDomainFromUrl';
|
import { getLoggingType } from '../utils/logging';
|
||||||
|
|
||||||
class WakaTimeCore {
|
class WakaTimeCore {
|
||||||
tabsWithDevtoolsOpen: Tabs.Tab[];
|
tabsWithDevtoolsOpen: Tabs.Tab[];
|
||||||
|
lastHeartbeat: Heartbeat | undefined;
|
||||||
|
lastHeartbeatSentAt = 0;
|
||||||
db: IDBPDatabase | undefined;
|
db: IDBPDatabase | undefined;
|
||||||
constructor() {
|
constructor() {
|
||||||
this.tabsWithDevtoolsOpen = [];
|
this.tabsWithDevtoolsOpen = [];
|
||||||
@@ -46,68 +48,57 @@ class WakaTimeCore {
|
|||||||
this.db = dbConnection;
|
this.db = dbConnection;
|
||||||
}
|
}
|
||||||
|
|
||||||
setTabsWithDevtoolsOpen(tabs: Tabs.Tab[]): void {
|
shouldSendHeartbeat(heartbeat: Heartbeat): boolean {
|
||||||
this.tabsWithDevtoolsOpen = tabs;
|
if (!this.lastHeartbeat) return true;
|
||||||
|
if (this.lastHeartbeat.entity !== heartbeat.entity) return true;
|
||||||
|
if (this.lastHeartbeatSentAt + 120000 < Date.now()) return true;
|
||||||
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
async getTotalTimeLoggedToday(api_key = ''): Promise<GrandTotal> {
|
async processHeartbeat(heartbeat: Heartbeat) {
|
||||||
const items = await browser.storage.sync.get({
|
const apiKey = await getApiKey();
|
||||||
apiUrl: config.apiUrl,
|
if (!apiKey) return changeExtensionState('notLogging');
|
||||||
summariesApiEndPoint: config.summariesApiEndPoint,
|
|
||||||
});
|
|
||||||
|
|
||||||
const today = moment().format('YYYY-MM-DD');
|
if (!this.shouldSendHeartbeat(heartbeat)) return;
|
||||||
const summariesAxiosPayload: AxiosResponse<SummariesPayload> = await axios.get(
|
|
||||||
`${items.apiUrl}${items.summariesApiEndPoint}`,
|
if (items.loggingStyle == 'deny') {
|
||||||
|
if (!contains(url, items.denyList as string)) {
|
||||||
|
await this.sendHeartbeat(
|
||||||
{
|
{
|
||||||
params: {
|
branch: null,
|
||||||
api_key,
|
hostname: items.hostname as string,
|
||||||
end: today,
|
project,
|
||||||
start: today,
|
url,
|
||||||
},
|
},
|
||||||
|
apiKey,
|
||||||
|
payload,
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
await changeExtensionState('ignored');
|
||||||
|
console.log(`${url} is on denyList.`);
|
||||||
|
}
|
||||||
|
} else if (items.loggingStyle == 'allow') {
|
||||||
|
const heartbeat = this.getHeartbeat(url, items.allowList as string);
|
||||||
|
if (heartbeat.url) {
|
||||||
|
await this.sendHeartbeat(
|
||||||
|
{
|
||||||
|
...heartbeat,
|
||||||
|
branch: null,
|
||||||
|
hostname: items.hostname as string,
|
||||||
|
project: heartbeat.project ?? project,
|
||||||
},
|
},
|
||||||
|
apiKey,
|
||||||
|
payload,
|
||||||
);
|
);
|
||||||
return summariesAxiosPayload.data.data[0].grand_total;
|
} else {
|
||||||
|
await changeExtensionState('ignored');
|
||||||
|
console.log(`${url} is not on allowList.`);
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
/**
|
throw Error(`Unknown logging styel: ${items.loggingStyle}`);
|
||||||
* Fetches the api token for logged users in wakatime website
|
|
||||||
*
|
|
||||||
* @returns {*}
|
|
||||||
*/
|
|
||||||
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(
|
|
||||||
`${items.apiUrl}${items.currentUserApiEndPoint}/get_api_key`,
|
|
||||||
);
|
|
||||||
return apiKeyResponse.data.data.api_key;
|
|
||||||
} catch (err: unknown) {
|
|
||||||
return '';
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Checks if the user is logged in.
|
|
||||||
*
|
|
||||||
* @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(
|
|
||||||
`${items.apiUrl}${items.currentUserApiEndPoint}`,
|
|
||||||
{ params: { api_key } },
|
|
||||||
);
|
|
||||||
return userPayload.data.data;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Depending on various factors detects the current active tab URL or domain,
|
* Depending on various factors detects the current active tab URL or domain,
|
||||||
* and sends it to WakaTime for logging.
|
* and sends it to WakaTime for logging.
|
||||||
@@ -118,13 +109,13 @@ class WakaTimeCore {
|
|||||||
return changeExtensionState('notLogging');
|
return changeExtensionState('notLogging');
|
||||||
}
|
}
|
||||||
const items = await browser.storage.sync.get({
|
const items = await browser.storage.sync.get({
|
||||||
blacklist: '',
|
allowList: '',
|
||||||
|
denyList: '',
|
||||||
hostname: config.hostname,
|
hostname: config.hostname,
|
||||||
loggingEnabled: config.loggingEnabled,
|
loggingEnabled: config.loggingEnabled,
|
||||||
loggingStyle: config.loggingStyle,
|
loggingStyle: config.loggingStyle,
|
||||||
socialMediaSites: config.socialMediaSites,
|
socialMediaSites: config.socialMediaSites,
|
||||||
trackSocialMedia: config.trackSocialMedia,
|
trackSocialMedia: config.trackSocialMedia,
|
||||||
whitelist: '',
|
|
||||||
});
|
});
|
||||||
if (items.loggingEnabled === true) {
|
if (items.loggingEnabled === true) {
|
||||||
await changeExtensionState('allGood');
|
await changeExtensionState('allGood');
|
||||||
@@ -159,12 +150,12 @@ class WakaTimeCore {
|
|||||||
const hostname = getDomain(url);
|
const hostname = getDomain(url);
|
||||||
if (!items.trackSocialMedia) {
|
if (!items.trackSocialMedia) {
|
||||||
if ((items.socialMediaSites as string[]).includes(hostname)) {
|
if ((items.socialMediaSites as string[]).includes(hostname)) {
|
||||||
return changeExtensionState('blacklisted');
|
return changeExtensionState('ignored');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Checks dev websites
|
// Checks dev websites
|
||||||
const project = generateProjectFromDevSites(url, html);
|
const project = getHeartbeatFromPage(url, html);
|
||||||
|
|
||||||
// Check if code reviewing
|
// Check if code reviewing
|
||||||
const codeReviewing = isCodeReviewing(url);
|
const codeReviewing = isCodeReviewing(url);
|
||||||
@@ -172,8 +163,8 @@ class WakaTimeCore {
|
|||||||
payload.category = 'code reviewing';
|
payload.category = 'code reviewing';
|
||||||
}
|
}
|
||||||
|
|
||||||
if (items.loggingStyle == 'blacklist') {
|
if (items.loggingStyle == 'deny') {
|
||||||
if (!contains(url, items.blacklist as string)) {
|
if (!contains(url, items.denyList as string)) {
|
||||||
await this.sendHeartbeat(
|
await this.sendHeartbeat(
|
||||||
{
|
{
|
||||||
branch: null,
|
branch: null,
|
||||||
@@ -185,13 +176,11 @@ class WakaTimeCore {
|
|||||||
payload,
|
payload,
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
await changeExtensionState('blacklisted');
|
await changeExtensionState('ignored');
|
||||||
console.log(`${url} is on a blacklist.`);
|
console.log(`${url} is on denyList.`);
|
||||||
}
|
}
|
||||||
}
|
} else if (items.loggingStyle == 'allow') {
|
||||||
|
const heartbeat = this.getHeartbeat(url, items.allowList as string);
|
||||||
if (items.loggingStyle == 'whitelist') {
|
|
||||||
const heartbeat = this.getHeartbeat(url, items.whitelist as string);
|
|
||||||
if (heartbeat.url) {
|
if (heartbeat.url) {
|
||||||
await this.sendHeartbeat(
|
await this.sendHeartbeat(
|
||||||
{
|
{
|
||||||
@@ -204,9 +193,11 @@ class WakaTimeCore {
|
|||||||
payload,
|
payload,
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
await changeExtensionState('whitelisted');
|
await changeExtensionState('ignored');
|
||||||
console.log(`${url} is not on a whitelist.`);
|
console.log(`${url} is not on allowList.`);
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
throw Error(`Unknown logging styel: ${items.loggingStyle}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -280,14 +271,14 @@ class WakaTimeCore {
|
|||||||
* @param debug
|
* @param debug
|
||||||
*/
|
*/
|
||||||
async sendHeartbeat(
|
async sendHeartbeat(
|
||||||
heartbeat: SendHeartbeat,
|
heartbeat: Heartbeat,
|
||||||
apiKey: string,
|
apiKey: string,
|
||||||
navigationPayload: Record<string, unknown>,
|
navigationPayload: Record<string, unknown>,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
console.log('Sending Heartbeat', heartbeat);
|
console.log('Sending Heartbeat', heartbeat);
|
||||||
let payload;
|
let payload;
|
||||||
|
|
||||||
const loggingType = await this.getLoggingType();
|
const loggingType = await getLoggingType();
|
||||||
// Get only the domain from the entity.
|
// Get only the domain from the entity.
|
||||||
// And send that in heartbeat
|
// And send that in heartbeat
|
||||||
if (loggingType == 'domain') {
|
if (loggingType == 'domain') {
|
||||||
@@ -310,20 +301,6 @@ class WakaTimeCore {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns a promise with logging type variable.
|
|
||||||
*
|
|
||||||
* @returns {*}
|
|
||||||
* @private
|
|
||||||
*/
|
|
||||||
async getLoggingType(): Promise<string> {
|
|
||||||
const items = await browser.storage.sync.get({
|
|
||||||
loggingType: config.loggingType,
|
|
||||||
});
|
|
||||||
|
|
||||||
return items.loggingType;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates payload for the heartbeat and returns it as JSON.
|
* Creates payload for the heartbeat and returns it as JSON.
|
||||||
*
|
*
|
||||||
@@ -333,8 +310,8 @@ class WakaTimeCore {
|
|||||||
* @returns {*}
|
* @returns {*}
|
||||||
* @private
|
* @private
|
||||||
*/
|
*/
|
||||||
async preparePayload(heartbeat: SendHeartbeat, type: string): Promise<Record<string, unknown>> {
|
async preparePayload(heartbeat: Heartbeat, type: string): Promise<Record<string, unknown>> {
|
||||||
const os = await this.getOperatingSystem();
|
const os = await getOperatingSystem();
|
||||||
let browserName = 'chrome';
|
let browserName = 'chrome';
|
||||||
let userAgent;
|
let userAgent;
|
||||||
if (IS_FIREFOX) {
|
if (IS_FIREFOX) {
|
||||||
@@ -359,14 +336,6 @@ class WakaTimeCore {
|
|||||||
return payload;
|
return payload;
|
||||||
}
|
}
|
||||||
|
|
||||||
getOperatingSystem(): Promise<string> {
|
|
||||||
return new Promise((resolve) => {
|
|
||||||
chrome.runtime.getPlatformInfo(function (info) {
|
|
||||||
resolve(`${info.os}_${info.arch}`);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Sends AJAX request with payload to the heartbeat API as JSON.
|
* Sends AJAX request with payload to the heartbeat API as JSON.
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
<meta charset="utf-8" />
|
<meta charset="utf-8" />
|
||||||
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
|
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
<title>WakaTime options</title>
|
<title>WakaTime Options</title>
|
||||||
|
|
||||||
<link href="public/css/app.css" rel="stylesheet" />
|
<link href="public/css/app.css" rel="stylesheet" />
|
||||||
</head>
|
</head>
|
||||||
|
|||||||
@@ -1,37 +1,26 @@
|
|||||||
// Generated by https://quicktype.io
|
export interface Heartbeat {
|
||||||
|
|
||||||
export interface HeartBeatsPayload {
|
|
||||||
data: Datum[];
|
|
||||||
end: string;
|
|
||||||
start: string;
|
|
||||||
timezone: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface Datum {
|
|
||||||
branch: string;
|
|
||||||
category: string;
|
|
||||||
created_at: string;
|
|
||||||
cursorpos: null;
|
|
||||||
dependencies: string;
|
|
||||||
entity: string;
|
|
||||||
id: string;
|
|
||||||
is_write: boolean;
|
|
||||||
language: string;
|
|
||||||
lineno: null;
|
|
||||||
lines: number;
|
|
||||||
machine_name_id: string;
|
|
||||||
project: string;
|
|
||||||
time: number;
|
|
||||||
type: string;
|
|
||||||
user_agent_id: string;
|
|
||||||
user_id: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface SendHeartbeat {
|
|
||||||
branch?: string | null;
|
branch?: string | null;
|
||||||
hostname: string;
|
category?: Category | null;
|
||||||
|
entity: string;
|
||||||
|
entityType: EntityType;
|
||||||
|
language?: string | null;
|
||||||
project?: string | null;
|
project?: string | null;
|
||||||
url: string;
|
}
|
||||||
|
|
||||||
|
export enum Category {
|
||||||
|
browsing = 'browsing',
|
||||||
|
code_reviewing = 'code reviewing',
|
||||||
|
coding = 'coding',
|
||||||
|
debugging = 'debugging',
|
||||||
|
designing = 'designing',
|
||||||
|
meeting = 'meeting',
|
||||||
|
}
|
||||||
|
|
||||||
|
export enum EntityType {
|
||||||
|
app = 'app',
|
||||||
|
domain = 'domain',
|
||||||
|
file = 'file',
|
||||||
|
url = 'url',
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ProjectDetails {
|
export interface ProjectDetails {
|
||||||
|
|||||||
@@ -1,12 +1,10 @@
|
|||||||
// Generated by https://quicktype.io
|
export interface Summaries {
|
||||||
|
data: Summary[];
|
||||||
export interface SummariesPayload {
|
|
||||||
data: Datum[];
|
|
||||||
end: string;
|
end: string;
|
||||||
start: string;
|
start: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Datum {
|
interface Summary {
|
||||||
categories: Category[];
|
categories: Category[];
|
||||||
dependencies: Category[];
|
dependencies: Category[];
|
||||||
editors: Category[];
|
editors: Category[];
|
||||||
@@ -18,7 +16,7 @@ export interface Datum {
|
|||||||
range: Range;
|
range: Range;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Category {
|
interface Category {
|
||||||
digital: string;
|
digital: string;
|
||||||
hours: number;
|
hours: number;
|
||||||
machine_name_id?: string;
|
machine_name_id?: string;
|
||||||
@@ -38,7 +36,7 @@ export interface GrandTotal {
|
|||||||
total_seconds: number;
|
total_seconds: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Range {
|
interface Range {
|
||||||
date: string;
|
date: string;
|
||||||
end: string;
|
end: string;
|
||||||
start: string;
|
start: string;
|
||||||
|
|||||||
@@ -20,13 +20,9 @@ export default async function changeExtensionState(state: ApiStates): Promise<vo
|
|||||||
await changeExtensionIcon(config.colors.notSignedIn);
|
await changeExtensionIcon(config.colors.notSignedIn);
|
||||||
await changeExtensionTooltip(config.tooltips.notSignedIn);
|
await changeExtensionTooltip(config.tooltips.notSignedIn);
|
||||||
break;
|
break;
|
||||||
case 'blacklisted':
|
case 'ignored':
|
||||||
await changeExtensionIcon(config.colors.notLogging);
|
await changeExtensionIcon(config.colors.notLogging);
|
||||||
await changeExtensionTooltip(config.tooltips.blacklisted);
|
await changeExtensionTooltip(config.tooltips.ignored);
|
||||||
break;
|
|
||||||
case 'whitelisted':
|
|
||||||
await changeExtensionIcon(config.colors.notLogging);
|
|
||||||
await changeExtensionTooltip(config.tooltips.whitelisted);
|
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
break;
|
break;
|
||||||
|
|||||||
158
src/utils/heartbeat.ts
Normal file
158
src/utils/heartbeat.ts
Normal file
@@ -0,0 +1,158 @@
|
|||||||
|
import { parse } from 'node-html-parser';
|
||||||
|
|
||||||
|
type ProjectNameExtractor = (url: string, html: string) => string | null;
|
||||||
|
|
||||||
|
const GitHub: ProjectNameExtractor = (url: string, html: string): string | null => {
|
||||||
|
const { hostname } = new URL(url);
|
||||||
|
const match = url.match(/(?<=github\.(?:com|dev)\/[^/]+\/)([^/?#]+)/);
|
||||||
|
|
||||||
|
if (match) {
|
||||||
|
if (hostname.endsWith('.com')) {
|
||||||
|
const root = parse(html);
|
||||||
|
const repoName = root
|
||||||
|
.querySelector('meta[name=octolytics-dimension-repository_nwo]')
|
||||||
|
?.getAttribute('content');
|
||||||
|
if (!repoName || repoName.split('/')[1] !== match[0]) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return match[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const GitLab: ProjectNameExtractor = (url: string, html: string): string | null => {
|
||||||
|
const match = url.match(/(?<=gitlab\.com\/[^/]+\/)([^/?#]+)/);
|
||||||
|
|
||||||
|
if (match) {
|
||||||
|
const root = parse(html);
|
||||||
|
const repoName = root.querySelector('body')?.getAttribute('data-project-full-path');
|
||||||
|
if (!repoName || repoName.split('/')[1] !== match[0]) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return match[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const BitBucket: ProjectNameExtractor = (url: string, html: string): string | null => {
|
||||||
|
const match = url.match(/(?<=bitbucket\.org\/[^/]+\/)([^/?#]+)/);
|
||||||
|
|
||||||
|
if (match) {
|
||||||
|
const root = parse(html);
|
||||||
|
// this regex extracts the project name from the title
|
||||||
|
// eg. title: jhondoe / my-test-repo — Bitbucket
|
||||||
|
const match2 = root.querySelector('title')?.textContent.match(/(?<=\/\s)([^/\s]+)(?=\s—)/);
|
||||||
|
if (match2 && match2[0] === match[0]) {
|
||||||
|
return match[0];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const TravisCI: ProjectNameExtractor = (url: string, html: string): string | null => {
|
||||||
|
const match = url.match(/(?<=app\.travis-ci\.com\/[^/]+\/[^/]+\/)([^/?#]+)/);
|
||||||
|
|
||||||
|
if (match) {
|
||||||
|
const root = parse(html);
|
||||||
|
const projectName = root.querySelector('#ember737')?.textContent;
|
||||||
|
if (projectName === match[0]) {
|
||||||
|
return match[0];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const CircleCI: ProjectNameExtractor = (url: string, html: string): string | null => {
|
||||||
|
const projectPageMatch = url.match(
|
||||||
|
/(?<=app\.circleci\.com\/projects\/[^/]+\/[^/]+\/[^/]+\/)([^/?#]+)/,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (projectPageMatch) {
|
||||||
|
const root = parse(html);
|
||||||
|
const seconndBreadcrumbLabel = root.querySelector(
|
||||||
|
'#__next > div:nth-child(2) > div > div > main > div > header > div:nth-child(1) > ol > li:nth-child(2) > div > div > span',
|
||||||
|
)?.textContent;
|
||||||
|
const seconndBreadcrumbValue = root.querySelector(
|
||||||
|
'#__next > div:nth-child(2) > div > div > main > div > header > div:nth-child(1) > ol > li:nth-child(2) > div > span',
|
||||||
|
)?.textContent;
|
||||||
|
if (seconndBreadcrumbLabel === 'Project' && seconndBreadcrumbValue === projectPageMatch[0]) {
|
||||||
|
return projectPageMatch[0];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const settingsPageMatch = url.match(
|
||||||
|
/(?<=app\.circleci\.com\/settings\/project\/[^/]+\/[^/]+\/)([^/?#]+)/,
|
||||||
|
);
|
||||||
|
if (settingsPageMatch) {
|
||||||
|
const root = parse(html);
|
||||||
|
const pageTitle = root.querySelector(
|
||||||
|
'#__next > div > div:nth-child(1) > header > div > div:nth-child(2) > h1',
|
||||||
|
)?.textContent;
|
||||||
|
const pageSubtitle = root.querySelector(
|
||||||
|
'#__next > div > div:nth-child(1) > header > div > div:nth-child(2) > div',
|
||||||
|
)?.textContent;
|
||||||
|
if (pageTitle === 'Project Settings' && pageSubtitle === settingsPageMatch[0]) {
|
||||||
|
return settingsPageMatch[0];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const Vercel: ProjectNameExtractor = (url: string, html: string): string | null => {
|
||||||
|
const match = url.match(/(?<=vercel\.com\/[^/]+\/)([^/?#]+)/);
|
||||||
|
|
||||||
|
if (match) {
|
||||||
|
const root = parse(html);
|
||||||
|
// this regex extracts the project name from the title
|
||||||
|
// eg. title: test-website - Overview – Vercel
|
||||||
|
const match2 = root.querySelector('title')?.textContent.match(/^[^\s]+(?=\s-\s)/);
|
||||||
|
if (match2 && match2[0] === match[0]) {
|
||||||
|
return match[0];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const ProjectNameExtractors: ProjectNameExtractor[] = [
|
||||||
|
GitHub,
|
||||||
|
GitLab,
|
||||||
|
BitBucket,
|
||||||
|
TravisCI,
|
||||||
|
CircleCI,
|
||||||
|
Vercel,
|
||||||
|
];
|
||||||
|
|
||||||
|
export const getHeartbeatFromPage = (): string | null => {
|
||||||
|
for (const projectNameExtractor of ProjectNameExtractors) {
|
||||||
|
const projectName = projectNameExtractor(url, html);
|
||||||
|
if (projectName) {
|
||||||
|
return projectName;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const CODE_REVIEW_URL_REG_LIST = [/github.com\/[^/]+\/[^/]+\/pull\/\d+\/files/];
|
||||||
|
|
||||||
|
export const isCodeReviewing = (url: string): boolean => {
|
||||||
|
for (const reg of CODE_REVIEW_URL_REG_LIST) {
|
||||||
|
if (url.match(reg)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getHtmlContentByTabId = async (tabId: number): Promise<string> => {
|
||||||
|
const response = (await browser.tabs.sendMessage(tabId, { message: 'get_html' })) as {
|
||||||
|
html: string;
|
||||||
|
};
|
||||||
|
return response.html;
|
||||||
|
};
|
||||||
@@ -1,148 +1,7 @@
|
|||||||
import { parse } from 'node-html-parser';
|
|
||||||
|
|
||||||
export const IS_EDGE = navigator.userAgent.includes('Edg');
|
export const IS_EDGE = navigator.userAgent.includes('Edg');
|
||||||
export const IS_FIREFOX = navigator.userAgent.includes('Firefox');
|
export const IS_FIREFOX = navigator.userAgent.includes('Firefox');
|
||||||
export const IS_CHROME = IS_EDGE === false && IS_FIREFOX === false;
|
export const IS_CHROME = IS_EDGE === false && IS_FIREFOX === false;
|
||||||
|
|
||||||
type ProjectNameExtractor = (url: string, html: string) => string | null;
|
|
||||||
|
|
||||||
const GitHub: ProjectNameExtractor = (url: string, html: string): string | null => {
|
|
||||||
const { hostname } = new URL(url);
|
|
||||||
const match = url.match(/(?<=github\.(?:com|dev)\/[^/]+\/)([^/?#]+)/);
|
|
||||||
|
|
||||||
if (match) {
|
|
||||||
if (hostname.endsWith('.com')) {
|
|
||||||
const root = parse(html);
|
|
||||||
const repoName = root
|
|
||||||
.querySelector('meta[name=octolytics-dimension-repository_nwo]')
|
|
||||||
?.getAttribute('content');
|
|
||||||
if (!repoName || repoName.split('/')[1] !== match[0]) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return match[0];
|
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
|
||||||
};
|
|
||||||
|
|
||||||
const GitLab: ProjectNameExtractor = (url: string, html: string): string | null => {
|
|
||||||
const match = url.match(/(?<=gitlab\.com\/[^/]+\/)([^/?#]+)/);
|
|
||||||
|
|
||||||
if (match) {
|
|
||||||
const root = parse(html);
|
|
||||||
const repoName = root.querySelector('body')?.getAttribute('data-project-full-path');
|
|
||||||
if (!repoName || repoName.split('/')[1] !== match[0]) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
return match[0];
|
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
|
||||||
};
|
|
||||||
|
|
||||||
const BitBucket: ProjectNameExtractor = (url: string, html: string): string | null => {
|
|
||||||
const match = url.match(/(?<=bitbucket\.org\/[^/]+\/)([^/?#]+)/);
|
|
||||||
|
|
||||||
if (match) {
|
|
||||||
const root = parse(html);
|
|
||||||
// this regex extracts the project name from the title
|
|
||||||
// eg. title: jhondoe / my-test-repo — Bitbucket
|
|
||||||
const match2 = root.querySelector('title')?.textContent.match(/(?<=\/\s)([^/\s]+)(?=\s—)/);
|
|
||||||
if (match2 && match2[0] === match[0]) {
|
|
||||||
return match[0];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
|
||||||
};
|
|
||||||
|
|
||||||
const TravisCI: ProjectNameExtractor = (url: string, html: string): string | null => {
|
|
||||||
const match = url.match(/(?<=app\.travis-ci\.com\/[^/]+\/[^/]+\/)([^/?#]+)/);
|
|
||||||
|
|
||||||
if (match) {
|
|
||||||
const root = parse(html);
|
|
||||||
const projectName = root.querySelector('#ember737')?.textContent;
|
|
||||||
if (projectName === match[0]) {
|
|
||||||
return match[0];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
|
||||||
};
|
|
||||||
|
|
||||||
const CircleCI: ProjectNameExtractor = (url: string, html: string): string | null => {
|
|
||||||
const projectPageMatch = url.match(
|
|
||||||
/(?<=app\.circleci\.com\/projects\/[^/]+\/[^/]+\/[^/]+\/)([^/?#]+)/,
|
|
||||||
);
|
|
||||||
|
|
||||||
if (projectPageMatch) {
|
|
||||||
const root = parse(html);
|
|
||||||
const seconndBreadcrumbLabel = root.querySelector(
|
|
||||||
'#__next > div:nth-child(2) > div > div > main > div > header > div:nth-child(1) > ol > li:nth-child(2) > div > div > span',
|
|
||||||
)?.textContent;
|
|
||||||
const seconndBreadcrumbValue = root.querySelector(
|
|
||||||
'#__next > div:nth-child(2) > div > div > main > div > header > div:nth-child(1) > ol > li:nth-child(2) > div > span',
|
|
||||||
)?.textContent;
|
|
||||||
if (seconndBreadcrumbLabel === 'Project' && seconndBreadcrumbValue === projectPageMatch[0]) {
|
|
||||||
return projectPageMatch[0];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const settingsPageMatch = url.match(
|
|
||||||
/(?<=app\.circleci\.com\/settings\/project\/[^/]+\/[^/]+\/)([^/?#]+)/,
|
|
||||||
);
|
|
||||||
if (settingsPageMatch) {
|
|
||||||
const root = parse(html);
|
|
||||||
const pageTitle = root.querySelector(
|
|
||||||
'#__next > div > div:nth-child(1) > header > div > div:nth-child(2) > h1',
|
|
||||||
)?.textContent;
|
|
||||||
const pageSubtitle = root.querySelector(
|
|
||||||
'#__next > div > div:nth-child(1) > header > div > div:nth-child(2) > div',
|
|
||||||
)?.textContent;
|
|
||||||
if (pageTitle === 'Project Settings' && pageSubtitle === settingsPageMatch[0]) {
|
|
||||||
return settingsPageMatch[0];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
|
||||||
};
|
|
||||||
|
|
||||||
const Vercel: ProjectNameExtractor = (url: string, html: string): string | null => {
|
|
||||||
const match = url.match(/(?<=vercel\.com\/[^/]+\/)([^/?#]+)/);
|
|
||||||
|
|
||||||
if (match) {
|
|
||||||
const root = parse(html);
|
|
||||||
// this regex extracts the project name from the title
|
|
||||||
// eg. title: test-website - Overview – Vercel
|
|
||||||
const match2 = root.querySelector('title')?.textContent.match(/^[^\s]+(?=\s-\s)/);
|
|
||||||
if (match2 && match2[0] === match[0]) {
|
|
||||||
return match[0];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
|
||||||
};
|
|
||||||
|
|
||||||
const ProjectNameExtractors: ProjectNameExtractor[] = [
|
|
||||||
GitHub,
|
|
||||||
GitLab,
|
|
||||||
BitBucket,
|
|
||||||
TravisCI,
|
|
||||||
CircleCI,
|
|
||||||
Vercel,
|
|
||||||
];
|
|
||||||
|
|
||||||
export const generateProjectFromDevSites = (url: string, html: string): string | null => {
|
|
||||||
for (const projectNameExtractor of ProjectNameExtractors) {
|
|
||||||
const projectName = projectNameExtractor(url, html);
|
|
||||||
if (projectName) {
|
|
||||||
return projectName;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
};
|
|
||||||
|
|
||||||
const CODE_REVIEW_URL_REG_LIST = [/github.com\/[^/]+\/[^/]+\/pull\/\d+\/files/];
|
const CODE_REVIEW_URL_REG_LIST = [/github.com\/[^/]+\/[^/]+\/pull\/\d+\/files/];
|
||||||
|
|
||||||
export const isCodeReviewing = (url: string): boolean => {
|
export const isCodeReviewing = (url: string): boolean => {
|
||||||
@@ -154,9 +13,10 @@ export const isCodeReviewing = (url: string): boolean => {
|
|||||||
return false;
|
return false;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const getHtmlContentByTabId = async (tabId: number): Promise<string> => {
|
export const getOperatingSystem = (): Promise<string> => {
|
||||||
const response = (await browser.tabs.sendMessage(tabId, { message: 'get_html' })) as {
|
return new Promise((resolve) => {
|
||||||
html: string;
|
chrome.runtime.getPlatformInfo(function (info) {
|
||||||
};
|
resolve(`${info.os}_${info.arch}`);
|
||||||
return response.html;
|
});
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|||||||
16
src/utils/logging.ts
Normal file
16
src/utils/logging.ts
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
import browser from 'webextension-polyfill';
|
||||||
|
import config from '../config/config';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns a promise with logging type variable.
|
||||||
|
*
|
||||||
|
* @returns {*}
|
||||||
|
* @private
|
||||||
|
*/
|
||||||
|
export const getLoggingType = async (): Promise<string> => {
|
||||||
|
const items = await browser.storage.sync.get({
|
||||||
|
loggingType: config.loggingType,
|
||||||
|
});
|
||||||
|
|
||||||
|
return items.loggingType;
|
||||||
|
};
|
||||||
71
src/utils/settings.ts
Normal file
71
src/utils/settings.ts
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
import browser from 'webextension-polyfill';
|
||||||
|
import config, { LoggingStyle, LoggingType, Theme } from '../config/config';
|
||||||
|
|
||||||
|
export interface Settings {
|
||||||
|
allowList: string[];
|
||||||
|
apiKey: string;
|
||||||
|
apiUrl: string;
|
||||||
|
denyList: string[];
|
||||||
|
hostname: string;
|
||||||
|
loggingStyle: LoggingStyle;
|
||||||
|
loggingType: LoggingType;
|
||||||
|
socialMediaSites: string[];
|
||||||
|
theme: Theme;
|
||||||
|
trackSocialMedia: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const getSettings = async (): Promise<Settings> => {
|
||||||
|
const settings = (await browser.storage.sync.get({
|
||||||
|
allowList: [],
|
||||||
|
apiKey: config.apiKey,
|
||||||
|
apiUrl: config.apiUrl,
|
||||||
|
blacklist: null,
|
||||||
|
denyList: [],
|
||||||
|
hostname: config.hostname,
|
||||||
|
loggingStyle: config.loggingStyle,
|
||||||
|
loggingType: config.loggingType,
|
||||||
|
socialMediaSites: config.socialMediaSites,
|
||||||
|
theme: config.theme,
|
||||||
|
trackSocialMedia: true,
|
||||||
|
whitelist: null,
|
||||||
|
})) as Omit<Settings, 'socialMediaSites'> & {
|
||||||
|
blacklist?: string;
|
||||||
|
socialMediaSites: string[] | string;
|
||||||
|
whitelist?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
// backwards compatibility
|
||||||
|
if (typeof settings.whitelist === 'string') {
|
||||||
|
settings.allowList = settings.whitelist.trim().split('\n');
|
||||||
|
await browser.storage.sync.set({ allowList: settings.allowList });
|
||||||
|
await browser.storage.sync.remove('whitelist');
|
||||||
|
}
|
||||||
|
if (typeof settings.blacklist === 'string') {
|
||||||
|
settings.denyList = settings.blacklist.trim().split('\n');
|
||||||
|
await browser.storage.sync.set({ denyList: settings.denyList });
|
||||||
|
await browser.storage.sync.remove('blacklist');
|
||||||
|
}
|
||||||
|
if (typeof settings.socialMediaSites === 'string') {
|
||||||
|
settings.socialMediaSites = settings.socialMediaSites.trim().split('\n');
|
||||||
|
await browser.storage.sync.set({
|
||||||
|
socialMediaSites: settings.socialMediaSites,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
allowList: settings.allowList,
|
||||||
|
apiKey: settings.apiKey,
|
||||||
|
apiUrl: settings.apiUrl,
|
||||||
|
denyList: settings.denyList,
|
||||||
|
hostname: settings.hostname,
|
||||||
|
loggingStyle: settings.loggingStyle,
|
||||||
|
loggingType: settings.loggingType,
|
||||||
|
socialMediaSites: settings.socialMediaSites,
|
||||||
|
theme: settings.theme,
|
||||||
|
trackSocialMedia: settings.trackSocialMedia,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
export const saveSettings = async (settings: Settings): Promise<void> => {
|
||||||
|
return browser.storage.sync.set(settings);
|
||||||
|
};
|
||||||
@@ -1,11 +1,31 @@
|
|||||||
import { AnyAction, Dispatch } from '@reduxjs/toolkit';
|
import { AnyAction, Dispatch } from '@reduxjs/toolkit';
|
||||||
|
import axios, { AxiosResponse } from 'axios';
|
||||||
|
|
||||||
|
import moment from 'moment';
|
||||||
import config from '../config/config';
|
import config from '../config/config';
|
||||||
import WakaTimeCore from '../core/WakaTimeCore';
|
|
||||||
import { setApiKey, setLoggingEnabled, setTotalTimeLoggedToday } from '../reducers/configReducer';
|
import { setApiKey, setLoggingEnabled, setTotalTimeLoggedToday } from '../reducers/configReducer';
|
||||||
import { setUser } from '../reducers/currentUser';
|
import { setUser } from '../reducers/currentUser';
|
||||||
import { getHtmlContentByTabId } from '.';
|
import { GrandTotal, Summaries } from '../types/summaries';
|
||||||
|
import { ApiKeyPayload, AxiosUserResponse, User } from '../types/user';
|
||||||
import changeExtensionState from './changeExtensionState';
|
import changeExtensionState from './changeExtensionState';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Checks if the user is logged in.
|
||||||
|
*
|
||||||
|
* @returns {*}
|
||||||
|
*/
|
||||||
|
const checkAuth = async (api_key = ''): Promise<User> => {
|
||||||
|
const items = await browser.storage.sync.get({
|
||||||
|
apiUrl: config.apiUrl,
|
||||||
|
currentUserApiEndPoint: config.currentUserApiEndPoint,
|
||||||
|
});
|
||||||
|
const userPayload: AxiosResponse<AxiosUserResponse> = await axios.get(
|
||||||
|
`${items.apiUrl}${items.currentUserApiEndPoint}`,
|
||||||
|
{ params: { api_key } },
|
||||||
|
);
|
||||||
|
return userPayload.data.data;
|
||||||
|
};
|
||||||
|
|
||||||
export const logUserIn = async (apiKey: string): Promise<void> => {
|
export const logUserIn = async (apiKey: string): Promise<void> => {
|
||||||
if (!apiKey) {
|
if (!apiKey) {
|
||||||
await changeExtensionState('notSignedIn');
|
await changeExtensionState('notSignedIn');
|
||||||
@@ -13,7 +33,7 @@ export const logUserIn = async (apiKey: string): Promise<void> => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await WakaTimeCore.checkAuth(apiKey);
|
await checkAuth(apiKey);
|
||||||
const items = await browser.storage.sync.get({ loggingEnabled: config.loggingEnabled });
|
const items = await browser.storage.sync.get({ loggingEnabled: config.loggingEnabled });
|
||||||
|
|
||||||
if (items.loggingEnabled === true) {
|
if (items.loggingEnabled === true) {
|
||||||
@@ -26,6 +46,47 @@ export const logUserIn = async (apiKey: string): Promise<void> => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fetches the api token for logged users in wakatime website
|
||||||
|
*
|
||||||
|
* @returns {*}
|
||||||
|
*/
|
||||||
|
const fetchApiKey = async (): Promise<string> => {
|
||||||
|
try {
|
||||||
|
const items = await browser.storage.sync.get({
|
||||||
|
apiUrl: config.apiUrl,
|
||||||
|
currentUserApiEndPoint: config.currentUserApiEndPoint,
|
||||||
|
});
|
||||||
|
|
||||||
|
const apiKeyResponse: AxiosResponse<ApiKeyPayload> = await axios.post(
|
||||||
|
`${items.apiUrl}${items.currentUserApiEndPoint}/get_api_key`,
|
||||||
|
);
|
||||||
|
return apiKeyResponse.data.data.api_key;
|
||||||
|
} catch (err: unknown) {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const getTotalTimeLoggedToday = async (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<Summaries> = await axios.get(
|
||||||
|
`${items.apiUrl}${items.summariesApiEndPoint}`,
|
||||||
|
{
|
||||||
|
params: {
|
||||||
|
api_key,
|
||||||
|
end: today,
|
||||||
|
start: today,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
return summariesAxiosPayload.data.data[0].grand_total;
|
||||||
|
};
|
||||||
|
|
||||||
export const fetchUserData = async (
|
export const fetchUserData = async (
|
||||||
apiKey: string,
|
apiKey: string,
|
||||||
dispatch: Dispatch<AnyAction>,
|
dispatch: Dispatch<AnyAction>,
|
||||||
@@ -36,7 +97,7 @@ export const fetchUserData = async (
|
|||||||
});
|
});
|
||||||
apiKey = storage.apiKey as string;
|
apiKey = storage.apiKey as string;
|
||||||
if (!apiKey) {
|
if (!apiKey) {
|
||||||
apiKey = await WakaTimeCore.fetchApiKey();
|
apiKey = await fetchApiKey();
|
||||||
if (apiKey) {
|
if (apiKey) {
|
||||||
await browser.storage.sync.set({ apiKey });
|
await browser.storage.sync.set({ apiKey });
|
||||||
}
|
}
|
||||||
@@ -51,8 +112,8 @@ export const fetchUserData = async (
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
const [data, totalTimeLoggedTodayResponse, items] = await Promise.all([
|
const [data, totalTimeLoggedTodayResponse, items] = await Promise.all([
|
||||||
WakaTimeCore.checkAuth(apiKey),
|
checkAuth(apiKey),
|
||||||
WakaTimeCore.getTotalTimeLoggedToday(apiKey),
|
getTotalTimeLoggedToday(apiKey),
|
||||||
browser.storage.sync.get({ loggingEnabled: config.loggingEnabled }),
|
browser.storage.sync.get({ loggingEnabled: config.loggingEnabled }),
|
||||||
]);
|
]);
|
||||||
dispatch(setUser(data));
|
dispatch(setUser(data));
|
||||||
@@ -65,21 +126,6 @@ export const fetchUserData = async (
|
|||||||
|
|
||||||
dispatch(setLoggingEnabled(items.loggingEnabled as boolean));
|
dispatch(setLoggingEnabled(items.loggingEnabled as boolean));
|
||||||
dispatch(setTotalTimeLoggedToday(totalTimeLoggedTodayResponse.text));
|
dispatch(setTotalTimeLoggedToday(totalTimeLoggedTodayResponse.text));
|
||||||
|
|
||||||
const tabs = await browser.tabs.query({
|
|
||||||
active: true,
|
|
||||||
currentWindow: true,
|
|
||||||
});
|
|
||||||
let html = '';
|
|
||||||
const tabId = tabs[0]?.id;
|
|
||||||
if (tabId) {
|
|
||||||
try {
|
|
||||||
html = await getHtmlContentByTabId(tabId);
|
|
||||||
// eslint-disable-next-line no-empty
|
|
||||||
} catch (error: unknown) {}
|
|
||||||
}
|
|
||||||
|
|
||||||
await WakaTimeCore.recordHeartbeat(html);
|
|
||||||
} catch (err: unknown) {
|
} catch (err: unknown) {
|
||||||
await changeExtensionState('notSignedIn');
|
await changeExtensionState('notSignedIn');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import { getHeartbeatFromPage } from './utils/heartbeat';
|
||||||
|
|
||||||
const oneMinute = 60000;
|
const oneMinute = 60000;
|
||||||
const fiveMinutes = 300000;
|
const fiveMinutes = 300000;
|
||||||
|
|
||||||
@@ -89,12 +91,8 @@ function debounce(func: () => void, timeout = oneMinute, maxWaitTime = fiveMinut
|
|||||||
}
|
}
|
||||||
|
|
||||||
const sendHeartbeat = debounce(async () => {
|
const sendHeartbeat = debounce(async () => {
|
||||||
const { hostname } = document.location;
|
const heartbeat = getHeartbeatFromPage();
|
||||||
|
chrome.runtime.sendMessage({ heartbeat: heartbeat, task: 'sendHeartbeat' });
|
||||||
const projectDetails = getParser[hostname]?.();
|
|
||||||
if (projectDetails) {
|
|
||||||
chrome.runtime.sendMessage({ projectDetails, recordHeartbeat: true });
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
chrome.runtime.onMessage.addListener((request: { message: string }, sender, sendResponse) => {
|
chrome.runtime.onMessage.addListener((request: { message: string }, sender, sendResponse) => {
|
||||||
|
|||||||
@@ -8,14 +8,14 @@ describe('contains', function () {
|
|||||||
expect(contains).to.be.a('function');
|
expect(contains).to.be.a('function');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should match url against blacklist and return true', function () {
|
it('should match url against denyList and return true', function () {
|
||||||
const list = 'localhost\ntest.com';
|
const list = 'localhost\ntest.com';
|
||||||
|
|
||||||
const url = 'http://localhost/fooapp';
|
const url = 'http://localhost/fooapp';
|
||||||
expect(contains(url, list)).to.equal(true);
|
expect(contains(url, list)).to.equal(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should not match url against blacklist and return false', function () {
|
it('should not match url against denyList and return false', function () {
|
||||||
const list = 'localhost2\ntest.com';
|
const list = 'localhost2\ntest.com';
|
||||||
|
|
||||||
const url = 'http://localhost/fooapp';
|
const url = 'http://localhost/fooapp';
|
||||||
|
|||||||
Reference in New Issue
Block a user