Merge pull request #265 from wakatime/feature/google-meet-support

Feature/google meet support
This commit is contained in:
Alan Hamlett
2024-08-27 23:20:40 +02:00
committed by GitHub
31 changed files with 12711 additions and 1006 deletions

54
package-lock.json generated
View File

@@ -23,6 +23,7 @@
"react-redux": "^8.0.5", "react-redux": "^8.0.5",
"react-transition-group": "^4.4.5", "react-transition-group": "^4.4.5",
"redux-logger": "^4.0.0", "redux-logger": "^4.0.0",
"uuid": "^10.0.0",
"webextension-polyfill": "^0.10.0" "webextension-polyfill": "^0.10.0"
}, },
"devDependencies": { "devDependencies": {
@@ -49,6 +50,7 @@
"@types/redux-logger": "^3.0.9", "@types/redux-logger": "^3.0.9",
"@types/shelljs": "^0.8.8", "@types/shelljs": "^0.8.8",
"@types/sinon-chrome": "^2.2.11", "@types/sinon-chrome": "^2.2.11",
"@types/uuid": "^10.0.0",
"@types/wait-on": "^5.2.0", "@types/wait-on": "^5.2.0",
"@types/webextension-polyfill": "^0.10.0", "@types/webextension-polyfill": "^0.10.0",
"@typescript-eslint/eslint-plugin": "^4.33.0", "@typescript-eslint/eslint-plugin": "^4.33.0",
@@ -4096,6 +4098,13 @@
"resolved": "https://registry.npmjs.org/@types/use-sync-external-store/-/use-sync-external-store-0.0.3.tgz", "resolved": "https://registry.npmjs.org/@types/use-sync-external-store/-/use-sync-external-store-0.0.3.tgz",
"integrity": "sha512-EwmlvuaxPNej9+T4v5AuBPJa2x2UOJVdjCtDHgcDqitUeOtjnJKJ+apYjVcAoBEMjKW1VVFGZLUb5+qqa09XFA==" "integrity": "sha512-EwmlvuaxPNej9+T4v5AuBPJa2x2UOJVdjCtDHgcDqitUeOtjnJKJ+apYjVcAoBEMjKW1VVFGZLUb5+qqa09XFA=="
}, },
"node_modules/@types/uuid": {
"version": "10.0.0",
"resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-10.0.0.tgz",
"integrity": "sha512-7gqG38EyHgyP1S+7+xomFtL+ZNHcKv6DwNaCZmJmo1vgMugyF3TCnXVg4t1uk89mLNwnLtnY3TpOpCOyp1/xHQ==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/wait-on": { "node_modules/@types/wait-on": {
"version": "5.3.1", "version": "5.3.1",
"resolved": "https://registry.npmjs.org/@types/wait-on/-/wait-on-5.3.1.tgz", "resolved": "https://registry.npmjs.org/@types/wait-on/-/wait-on-5.3.1.tgz",
@@ -18779,6 +18788,17 @@
"node": ">=0.8" "node": ">=0.8"
} }
}, },
"node_modules/request/node_modules/uuid": {
"version": "3.4.0",
"resolved": "https://registry.npmjs.org/uuid/-/uuid-3.4.0.tgz",
"integrity": "sha512-HjSDRw6gZE5JMggctHBcjVak08+KEVhSIiDzFnT9S9aegmp85S/bReBVTb4QTFaRNptJ9kuYaNhnbNEOkbKb/A==",
"deprecated": "Please upgrade to version 7 or higher. Older versions may use Math.random() in certain circumstances, which is known to be problematic. See https://v8.dev/blog/math-random for details.",
"dev": true,
"license": "MIT",
"bin": {
"uuid": "bin/uuid"
}
},
"node_modules/require-at": { "node_modules/require-at": {
"version": "1.0.6", "version": "1.0.6",
"resolved": "https://registry.npmjs.org/require-at/-/require-at-1.0.6.tgz", "resolved": "https://registry.npmjs.org/require-at/-/require-at-1.0.6.tgz",
@@ -21388,13 +21408,16 @@
"dev": true "dev": true
}, },
"node_modules/uuid": { "node_modules/uuid": {
"version": "3.4.0", "version": "10.0.0",
"resolved": "https://registry.npmjs.org/uuid/-/uuid-3.4.0.tgz", "resolved": "https://registry.npmjs.org/uuid/-/uuid-10.0.0.tgz",
"integrity": "sha512-HjSDRw6gZE5JMggctHBcjVak08+KEVhSIiDzFnT9S9aegmp85S/bReBVTb4QTFaRNptJ9kuYaNhnbNEOkbKb/A==", "integrity": "sha512-8XkAphELsDnEGrDxUOHB3RGvXz6TeuYSGEZBOjtTtPm2lwhGBjLgOzLHB63IUWfBpNucQjND6d3AOudO+H3RWQ==",
"deprecated": "Please upgrade to version 7 or higher. Older versions may use Math.random() in certain circumstances, which is known to be problematic. See https://v8.dev/blog/math-random for details.", "funding": [
"dev": true, "https://github.com/sponsors/broofa",
"https://github.com/sponsors/ctavan"
],
"license": "MIT",
"bin": { "bin": {
"uuid": "bin/uuid" "uuid": "dist/bin/uuid"
} }
}, },
"node_modules/v8-compile-cache": { "node_modules/v8-compile-cache": {
@@ -25578,6 +25601,12 @@
"resolved": "https://registry.npmjs.org/@types/use-sync-external-store/-/use-sync-external-store-0.0.3.tgz", "resolved": "https://registry.npmjs.org/@types/use-sync-external-store/-/use-sync-external-store-0.0.3.tgz",
"integrity": "sha512-EwmlvuaxPNej9+T4v5AuBPJa2x2UOJVdjCtDHgcDqitUeOtjnJKJ+apYjVcAoBEMjKW1VVFGZLUb5+qqa09XFA==" "integrity": "sha512-EwmlvuaxPNej9+T4v5AuBPJa2x2UOJVdjCtDHgcDqitUeOtjnJKJ+apYjVcAoBEMjKW1VVFGZLUb5+qqa09XFA=="
}, },
"@types/uuid": {
"version": "10.0.0",
"resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-10.0.0.tgz",
"integrity": "sha512-7gqG38EyHgyP1S+7+xomFtL+ZNHcKv6DwNaCZmJmo1vgMugyF3TCnXVg4t1uk89mLNwnLtnY3TpOpCOyp1/xHQ==",
"dev": true
},
"@types/wait-on": { "@types/wait-on": {
"version": "5.3.1", "version": "5.3.1",
"resolved": "https://registry.npmjs.org/@types/wait-on/-/wait-on-5.3.1.tgz", "resolved": "https://registry.npmjs.org/@types/wait-on/-/wait-on-5.3.1.tgz",
@@ -36628,6 +36657,12 @@
"psl": "^1.1.28", "psl": "^1.1.28",
"punycode": "^2.1.1" "punycode": "^2.1.1"
} }
},
"uuid": {
"version": "3.4.0",
"resolved": "https://registry.npmjs.org/uuid/-/uuid-3.4.0.tgz",
"integrity": "sha512-HjSDRw6gZE5JMggctHBcjVak08+KEVhSIiDzFnT9S9aegmp85S/bReBVTb4QTFaRNptJ9kuYaNhnbNEOkbKb/A==",
"dev": true
} }
} }
}, },
@@ -38625,10 +38660,9 @@
"dev": true "dev": true
}, },
"uuid": { "uuid": {
"version": "3.4.0", "version": "10.0.0",
"resolved": "https://registry.npmjs.org/uuid/-/uuid-3.4.0.tgz", "resolved": "https://registry.npmjs.org/uuid/-/uuid-10.0.0.tgz",
"integrity": "sha512-HjSDRw6gZE5JMggctHBcjVak08+KEVhSIiDzFnT9S9aegmp85S/bReBVTb4QTFaRNptJ9kuYaNhnbNEOkbKb/A==", "integrity": "sha512-8XkAphELsDnEGrDxUOHB3RGvXz6TeuYSGEZBOjtTtPm2lwhGBjLgOzLHB63IUWfBpNucQjND6d3AOudO+H3RWQ=="
"dev": true
}, },
"v8-compile-cache": { "v8-compile-cache": {
"version": "2.3.0", "version": "2.3.0",

View File

@@ -44,6 +44,7 @@
"react-redux": "^8.0.5", "react-redux": "^8.0.5",
"react-transition-group": "^4.4.5", "react-transition-group": "^4.4.5",
"redux-logger": "^4.0.0", "redux-logger": "^4.0.0",
"uuid": "^10.0.0",
"webextension-polyfill": "^0.10.0" "webextension-polyfill": "^0.10.0"
}, },
"devDependencies": { "devDependencies": {
@@ -70,6 +71,7 @@
"@types/redux-logger": "^3.0.9", "@types/redux-logger": "^3.0.9",
"@types/shelljs": "^0.8.8", "@types/shelljs": "^0.8.8",
"@types/sinon-chrome": "^2.2.11", "@types/sinon-chrome": "^2.2.11",
"@types/uuid": "^10.0.0",
"@types/wait-on": "^5.2.0", "@types/wait-on": "^5.2.0",
"@types/webextension-polyfill": "^0.10.0", "@types/webextension-polyfill": "^0.10.0",
"@typescript-eslint/eslint-plugin": "^4.33.0", "@typescript-eslint/eslint-plugin": "^4.33.0",

View File

@@ -1,7 +1,5 @@
import browser from 'webextension-polyfill'; import browser from 'webextension-polyfill';
import WakaTimeCore from './core/WakaTimeCore'; import WakaTimeCore from './core/WakaTimeCore';
import { PostHeartbeatMessage } from './types/heartbeats';
import { getHtmlContentByTabId } from './utils';
// Add a listener to resolve alarms // Add a listener to resolve alarms
browser.alarms.onAlarm.addListener(async (alarm) => { browser.alarms.onAlarm.addListener(async (alarm) => {
@@ -12,7 +10,7 @@ browser.alarms.onAlarm.addListener(async (alarm) => {
// Checks if the user is online and if there are cached heartbeats requests, // Checks if the user is online and if there are cached heartbeats requests,
// if so then procedd to send these payload to wakatime api // if so then procedd to send these payload to wakatime api
if (navigator.onLine) { if (navigator.onLine) {
await WakaTimeCore.sendCachedHeartbeatsRequest(); await WakaTimeCore.sendHeartbeats();
} }
} }
}); });
@@ -24,9 +22,7 @@ browser.alarms.create('heartbeatAlarm', { periodInMinutes: 2 });
* Whenever a active tab is changed it records a heartbeat with that tab url. * Whenever a active tab is changed it records a heartbeat with that tab url.
*/ */
browser.tabs.onActivated.addListener(async (activeInfo) => { browser.tabs.onActivated.addListener(async (activeInfo) => {
console.log('recording a heartbeat - active tab changed'); await WakaTimeCore.handleActivity(activeInfo.tabId);
const html = await getHtmlContentByTabId(activeInfo.tabId);
await WakaTimeCore.recordHeartbeat(html);
}); });
/** /**
@@ -34,18 +30,15 @@ browser.tabs.onActivated.addListener(async (activeInfo) => {
*/ */
browser.windows.onFocusChanged.addListener(async (windowId) => { browser.windows.onFocusChanged.addListener(async (windowId) => {
if (windowId != browser.windows.WINDOW_ID_NONE) { if (windowId != browser.windows.WINDOW_ID_NONE) {
console.log('recording a heartbeat - active window changed');
const tabs: browser.Tabs.Tab[] = await browser.tabs.query({ const tabs: browser.Tabs.Tab[] = await browser.tabs.query({
active: true, active: true,
currentWindow: true, currentWindow: true,
}); });
let html = '';
const tabId = tabs[0]?.id; const tabId = tabs[0]?.id;
if (tabId) { if (tabId) {
html = await getHtmlContentByTabId(tabId); await WakaTimeCore.handleActivity(tabId);
} }
await WakaTimeCore.recordHeartbeat(html);
} }
}); });
@@ -62,8 +55,7 @@ browser.tabs.onUpdated.addListener(async (tabId, changeInfo) => {
}); });
// If tab updated is the same as active tab // If tab updated is the same as active tab
if (tabId == tabs[0]?.id) { if (tabId == tabs[0]?.id) {
const html = await getHtmlContentByTabId(tabId); await WakaTimeCore.handleActivity(tabs[0].id);
await WakaTimeCore.recordHeartbeat(html);
} }
} }
}); });
@@ -76,12 +68,10 @@ self.addEventListener('activate', async () => {
await WakaTimeCore.createDB(); await WakaTimeCore.createDB();
}); });
browser.runtime.onMessage.addListener(async (request: PostHeartbeatMessage, sender) => { browser.runtime.onMessage.addListener(async (request: { task: string }, sender) => {
if (request.recordHeartbeat === true) { if (request.task === 'handleActivity') {
if (sender.tab?.id) { if (!sender.tab?.id) return;
const html = await getHtmlContentByTabId(sender.tab.id); await WakaTimeCore.handleActivity(sender.tab.id);
await WakaTimeCore.recordHeartbeat(html, request.projectDetails);
}
} }
}); });

View File

@@ -4,7 +4,7 @@ import { configLogout, setLoggingEnabled } from '../reducers/configReducer';
import { userLogout } from '../reducers/currentUser'; import { userLogout } from '../reducers/currentUser';
import { ReduxSelector } from '../types/store'; import { ReduxSelector } from '../types/store';
import { User } from '../types/user'; import { User } from '../types/user';
import changeExtensionState from '../utils/changeExtensionState'; import changeExtensionState from '../utils/changeExtensionStatus';
export interface MainListProps { export interface MainListProps {
loggingEnabled: boolean; loggingEnabled: boolean;
@@ -40,7 +40,7 @@ export default function MainList({
const disableLogging = async (): Promise<void> => { const disableLogging = async (): Promise<void> => {
dispatch(setLoggingEnabled(false)); dispatch(setLoggingEnabled(false));
await browser.storage.sync.set({ loggingEnabled: false }); await browser.storage.sync.set({ loggingEnabled: false });
await changeExtensionState('notLogging'); await changeExtensionState('trackingDisabled');
}; };
return ( return (

View File

@@ -1,78 +1,43 @@
import React, { useEffect, useRef, useState } from 'react'; 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 apiKeyInvalid from '../utils/apiKey'; import apiKeyInvalid from '../utils/apiKey';
import { IS_CHROME } from '../utils/operatingSystem';
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: [],
extensionStatus: 'allGood',
hostname: '', hostname: '',
loading: false, loading: false,
loggingEnabled: true,
loggingStyle: config.loggingStyle, loggingStyle: config.loggingStyle,
loggingType: config.loggingType, loggingType: config.loggingType,
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 +48,62 @@ 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, extensionStatus: state.extensionStatus,
hostname, hostname: state.hostname,
loggingStyle, loggingEnabled: state.loggingEnabled,
loggingType, loggingStyle: state.loggingStyle,
socialMediaSites, loggingType: state.loggingType,
theme, socialMediaSites: state.socialMediaSites,
trackSocialMedia, theme: state.theme,
whitelist, trackSocialMedia: state.trackSocialMedia,
});
// 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 +112,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&#10;http://myproject.com/MyProject" placeholder="http://google.com&#10;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 +166,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 +183,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 +198,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>

View File

@@ -10,7 +10,7 @@ import NavBar from './NavBar';
export default function WakaTime(): JSX.Element { export default function WakaTime(): JSX.Element {
const dispatch = useDispatch(); const dispatch = useDispatch();
const [extensionState, setExtensionState] = useState(''); const [extensionStatus, setExtensionStatus] = useState('');
const { const {
apiKey: apiKeyFromRedux, apiKey: apiKeyFromRedux,
@@ -21,8 +21,8 @@ export default function WakaTime(): JSX.Element {
useEffect(() => { useEffect(() => {
const fetchData = async () => { const fetchData = async () => {
await fetchUserData(apiKeyFromRedux, dispatch); await fetchUserData(apiKeyFromRedux, dispatch);
const items = await browser.storage.sync.get({ extensionState: '' }); const items = await browser.storage.sync.get({ extensionStatus: '' });
setExtensionState(items.extensionState as string); setExtensionStatus(items.extensionStatus as string);
}; };
void fetchData(); void fetchData();
}, []); }, []);
@@ -32,7 +32,7 @@ export default function WakaTime(): JSX.Element {
return ( return (
<div className="py-4 px-2 pt-0"> <div className="py-4 px-2 pt-0">
<NavBar /> <NavBar />
{isApiKeyValid && extensionState === 'notSignedIn' && ( {isApiKeyValid && extensionStatus === 'notSignedIn' && (
<Alert <Alert
type={config.alert.failure.type} type={config.alert.failure.type}
text={'Invalid API key or API url'} text={'Invalid API key or API url'}

View File

@@ -29,8 +29,8 @@ describe('wakatime config', () => {
"colors": { "colors": {
"allGood": "", "allGood": "",
"lightTheme": "white", "lightTheme": "white",
"notLogging": "gray",
"notSignedIn": "red", "notSignedIn": "red",
"trackingDisabled": "gray",
}, },
"currentUserApiEndPoint": "/users/current", "currentUserApiEndPoint": "/users/current",
"detectionIntervalInSeconds": 60, "detectionIntervalInSeconds": 60,
@@ -46,10 +46,10 @@ describe('wakatime config', () => {
"udemy.com", "udemy.com",
"w3schools.com", "w3schools.com",
], ],
"heartbeatApiEndPoint": "/users/current/heartbeats", "heartbeatApiEndPoint": "/users/current/heartbeats.bulk",
"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",
@@ -71,19 +71,17 @@ describe('wakatime config', () => {
], ],
"states": [ "states": [
"allGood", "allGood",
"notLogging", "trackingDisabled",
"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",
"notSignedIn": "Not signed In", "notSignedIn": "Not signed In",
"whitelisted": "This URL is not on your whitelist", "trackingDisabled": "Not logging",
}, },
"trackSocialMedia": true, "trackSocialMedia": true,
"version": "test-version", "version": "test-version",

View File

@@ -3,16 +3,18 @@ import browser from 'webextension-polyfill';
/** /**
* Logging * Logging
*/ */
export type ApiStates = 'allGood' | 'notLogging' | 'notSignedIn' | 'blacklisted' | 'whitelisted'; export type ExtensionStatus = 'allGood' | 'trackingDisabled' | '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.
*/ */
@@ -33,18 +35,17 @@ interface SuccessOrFailAlert {
interface Colors { interface Colors {
allGood: ''; allGood: '';
lightTheme: 'white'; lightTheme: 'white';
notLogging: 'gray';
notSignedIn: 'red'; notSignedIn: 'red';
trackingDisabled: 'gray';
} }
/** /**
* Tooltip messages * Tooltip messages
*/ */
interface Tooltips { interface Tooltips {
allGood: string; allGood: string;
blacklisted: string; ignored: string;
notLogging: string;
notSignedIn: string; notSignedIn: string;
whitelisted: string; trackingDisabled: string;
} }
export interface Config { export interface Config {
@@ -89,7 +90,7 @@ export interface Config {
name: string; name: string;
nonTrackableSites: string[]; nonTrackableSites: string[];
socialMediaSites: string[]; socialMediaSites: string[];
states: ApiStates[]; states: ExtensionStatus[];
/** /**
* Get stats from the wakatime api * Get stats from the wakatime api
*/ */
@@ -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;
/** /**
@@ -125,8 +126,8 @@ const config: Config = {
colors: { colors: {
allGood: '', allGood: '',
lightTheme: 'white', lightTheme: 'white',
notLogging: 'gray',
notSignedIn: 'red', notSignedIn: 'red',
trackingDisabled: 'gray',
}, },
currentUserApiEndPoint: process.env.CURRENT_USER_API_URL ?? '/users/current', currentUserApiEndPoint: process.env.CURRENT_USER_API_URL ?? '/users/current',
@@ -146,13 +147,13 @@ const config: Config = {
'w3schools.com', 'w3schools.com',
], ],
heartbeatApiEndPoint: process.env.HEARTBEAT_API_URL ?? '/users/current/heartbeats', heartbeatApiEndPoint: process.env.HEARTBEAT_API_URL ?? '/users/current/heartbeats.bulk',
hostname: '', hostname: '',
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', 'trackingDisabled', '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',
notSignedIn: 'Not signed In', notSignedIn: 'Not signed In',
whitelisted: 'This URL is not on your whitelist', trackingDisabled: 'Not logging',
}, },
trackSocialMedia: true, trackSocialMedia: true,

View File

@@ -1,21 +1,23 @@
import { IDBPDatabase, openDB } from 'idb';
import browser, { Tabs } from 'webextension-polyfill';
/* eslint-disable no-fallthrough */ /* eslint-disable no-fallthrough */
/* eslint-disable default-case */ /* eslint-disable default-case */
import axios, { AxiosResponse } from 'axios';
import { IDBPDatabase, openDB } from 'idb';
import moment from 'moment'; import moment from 'moment';
import browser, { Tabs } from 'webextension-polyfill'; import { v4 as uuid4 } from 'uuid';
import config from '../config/config'; import { OptionalHeartbeat } from '../types/sites';
import { SendHeartbeat } from '../types/heartbeats'; import { changeExtensionStatus } from '../utils/changeExtensionStatus';
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 changeExtensionState from '../utils/changeExtensionState';
import contains from '../utils/contains';
import getDomainFromUrl, { getDomain } from '../utils/getDomainFromUrl'; import getDomainFromUrl, { getDomain } from '../utils/getDomainFromUrl';
import { getOperatingSystem, IS_EDGE, IS_FIREFOX } from '../utils/operatingSystem';
import { getSettings, Settings } from '../utils/settings';
import config, { ExtensionStatus } from '../config/config';
import { EntityType, Heartbeat, HeartbeatsBulkResponse } from '../types/heartbeats';
class WakaTimeCore { class WakaTimeCore {
tabsWithDevtoolsOpen: Tabs.Tab[]; tabsWithDevtoolsOpen: Tabs.Tab[];
lastHeartbeat: Heartbeat | undefined;
lastHeartbeatSentAt = 0;
lastExtensionState: ExtensionStatus = 'allGood';
db: IDBPDatabase | undefined; db: IDBPDatabase | undefined;
constructor() { constructor() {
this.tabsWithDevtoolsOpen = []; this.tabsWithDevtoolsOpen = [];
@@ -29,312 +31,227 @@ class WakaTimeCore {
const dbConnection = await openDB('wakatime', 1, { const dbConnection = await openDB('wakatime', 1, {
upgrade(db, oldVersion) { upgrade(db, oldVersion) {
// Create a store of objects // Create a store of objects
const store = db.createObjectStore('cacheHeartbeats', { const store = db.createObjectStore('heartbeatQueue', {
// The `time` property of the object will be the key, and be incremented automatically keyPath: 'id',
keyPath: 'time',
}); });
// Switch over the oldVersion, *without breaks*, to allow the database to be incrementally upgraded. // Switch over the oldVersion, *without breaks*, to allow the database to be incrementally upgraded.
switch (oldVersion) { switch (oldVersion) {
case 0: case 0:
// Placeholder to execute when database is created (oldVersion is 0) // Placeholder to execute when database is created (oldVersion is 0)
case 1: case 1:
// Create an index called `type` based on the `type` property of objects in the store store.createIndex('id', 'id');
store.createIndex('time', 'time');
} }
}, },
}); });
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> { canSendHeartbeat(url: string, settings: Settings): boolean {
const items = await browser.storage.sync.get({ for (const site of config.nonTrackableSites) {
apiUrl: config.apiUrl, if (url.startsWith(site)) {
summariesApiEndPoint: config.summariesApiEndPoint, // Don't send a heartbeat on sites like 'chrome://newtab/' or 'about:newtab'
}); return false;
}
}
const today = moment().format('YYYY-MM-DD'); if (!settings.trackSocialMedia) {
const summariesAxiosPayload: AxiosResponse<SummariesPayload> = await axios.get( const domain = getDomain(url);
`${items.apiUrl}${items.summariesApiEndPoint}`, if (
{ settings.socialMediaSites.find((pattern) => {
params: { const re = new RegExp(pattern.replace(/\*/g, '.*'));
api_key, return re.test(domain);
end: today, }) !== undefined
start: today, ) {
}, return false;
}, }
); }
return summariesAxiosPayload.data.data[0].grand_total;
}
/** if (settings.loggingStyle === 'deny') {
* Fetches the api token for logged users in wakatime website return (
* settings.denyList.find((pattern) => {
* @returns {*} const re = new RegExp(pattern.replace(/\*/g, '.*'));
*/ return re.test(url);
async fetchApiKey(): Promise<string> { }) == undefined
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 '';
} }
} return (
settings.allowList.find((pattern) => {
/** const re = new RegExp(pattern.replace(/\*/g, '.*'));
* Checks if the user is logged in. return re.test(url);
* }) !== undefined
* @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;
} }
/** async handleActivity(tabId: number) {
* Depending on various factors detects the current active tab URL or domain, const settings = await getSettings();
* and sends it to WakaTime for logging. if (!settings.loggingEnabled) {
*/ await changeExtensionStatus('trackingDisabled');
async recordHeartbeat(html: string, payload: Record<string, unknown> = {}): Promise<void> { return;
const apiKey = await getApiKey();
if (!apiKey) {
return changeExtensionState('notLogging');
} }
const items = await browser.storage.sync.get({
blacklist: '', const activeTab = await this.getCurrentTab(tabId);
hostname: config.hostname, if (!activeTab) return;
loggingEnabled: config.loggingEnabled,
loggingStyle: config.loggingStyle, const url = activeTab.url as string;
socialMediaSites: config.socialMediaSites,
trackSocialMedia: config.trackSocialMedia, if (!this.canSendHeartbeat(url, settings)) {
whitelist: '', await changeExtensionStatus('ignored');
return;
}
if (settings.extensionStatus !== 'notSignedIn') {
await changeExtensionStatus('allGood');
}
const heartbeat = await this.buildHeartbeat(url, settings, activeTab);
if (!this.shouldSendHeartbeat(heartbeat)) return;
// append heartbeat to queue
await this.db?.add('heartbeatQueue', heartbeat);
await this.sendHeartbeats();
}
async getCurrentTab(tabId: number): Promise<browser.Tabs.Tab | undefined> {
const tabs: browser.Tabs.Tab[] = await browser.tabs.query({
active: true,
currentWindow: true,
}); });
if (items.loggingEnabled === true) { const activeTab = tabs[0];
await changeExtensionState('allGood'); if (tabId !== activeTab.id) return;
let newState = ''; return activeTab;
// Detects we are running this code in the extension scope
if (browser.idle as browser.Idle.Static | undefined) {
newState = await browser.idle.queryState(config.detectionIntervalInSeconds);
if (newState !== 'active') {
return changeExtensionState('notLogging');
}
}
// Get current tab URL.
let url = '';
if (browser.tabs as browser.Tabs.Static | undefined) {
const tabs = await browser.tabs.query({ active: true, currentWindow: true });
if (tabs.length == 0) return;
const currentActiveTab = tabs[0];
url = currentActiveTab.url as string;
} else {
url = document.URL;
}
for (const site of config.nonTrackableSites) {
if (url.startsWith(site)) {
// Don't send a heartbeat on sites like 'chrome://newtab/' or 'about:newtab'
return;
}
}
const hostname = getDomain(url);
if (!items.trackSocialMedia) {
if ((items.socialMediaSites as string[]).includes(hostname)) {
return changeExtensionState('blacklisted');
}
}
// Checks dev websites
const project = generateProjectFromDevSites(url, html);
// Check if code reviewing
const codeReviewing = isCodeReviewing(url);
if (codeReviewing) {
payload.category = 'code reviewing';
}
if (items.loggingStyle == 'blacklist') {
if (!contains(url, items.blacklist as string)) {
await this.sendHeartbeat(
{
branch: null,
hostname: items.hostname as string,
project,
url,
},
apiKey,
payload,
);
} else {
await changeExtensionState('blacklisted');
console.log(`${url} is on a blacklist.`);
}
}
if (items.loggingStyle == 'whitelist') {
const heartbeat = this.getHeartbeat(url, items.whitelist as string);
if (heartbeat.url) {
await this.sendHeartbeat(
{
...heartbeat,
branch: null,
hostname: items.hostname as string,
project: heartbeat.project ?? project,
},
apiKey,
payload,
);
} else {
await changeExtensionState('whitelisted');
console.log(`${url} is not on a whitelist.`);
}
}
}
} }
/** async buildHeartbeat(url: string, settings: Settings, tab: browser.Tabs.Tab): Promise<Heartbeat> {
* Creates an array from list using \n as delimiter if (!tab.id) {
* and checks if any element in list is contained in the url. throw Error('Missing tab id.');
* Also checks if element is assigned to a project using @@ as delimiter
*
* @param url
* @param list
* @returns {object}
*/
getHeartbeat(url: string, list: string) {
const projectIndicatorCharacters = '@@';
const lines = list.split('\n');
for (let i = 0; i < lines.length; i++) {
// strip (http:// or https://) and trailing (`/` or `@@`)
const cleanLine = lines[i]
.trim()
.replace(/(\/|@@)$/, '')
.replace(/^(?:https?:\/\/)?/i, '');
if (cleanLine === '') continue;
const projectIndicatorIndex = cleanLine.lastIndexOf(projectIndicatorCharacters);
const projectIndicatorExists = projectIndicatorIndex > -1;
let projectName = null;
let urlFromLine = cleanLine;
if (projectIndicatorExists) {
const start = projectIndicatorIndex + projectIndicatorCharacters.length;
projectName = cleanLine.substring(start);
urlFromLine = cleanLine
.replace(cleanLine.substring(projectIndicatorIndex), '')
.replace(/\/$/, '');
}
const cleanUrl = url
.trim()
.replace(/(\/|@@)$/, '')
.replace(/^(?:https?:\/\/)?/i, '');
const startsWithUrl = cleanUrl.toLowerCase().includes(urlFromLine.toLowerCase());
if (startsWithUrl) {
return {
project: projectName,
url,
};
}
const lineRe = new RegExp(cleanLine.replace('.', '.').replace('*', '.*'));
// If url matches the current line return true
if (lineRe.test(url)) {
return {
project: null,
url,
};
}
} }
const heartbeat = (
(await browser.tabs.sendMessage(tab.id, { task: 'getHeartbeatFromPage', url })) as {
heartbeat?: OptionalHeartbeat;
}
).heartbeat;
const entity = settings.loggingType === 'domain' ? getDomainFromUrl(url) : url;
return { return {
project: null, branch: heartbeat?.branch ?? '<<LAST_BRANCH>>',
url: null, category: heartbeat?.category,
entity: heartbeat?.entity ?? entity,
id: uuid4(),
language: heartbeat?.language,
plugin: heartbeat?.plugin,
project: heartbeat?.project ?? '<<LAST_PROJECT>>',
time: this.getCurrentTime(),
type: heartbeat?.entityType ?? (settings.loggingType as EntityType),
}; };
} }
/** getCurrentTime(): string {
* Given the heartbeat and logging type it creates a payload and const m = moment();
* sends an ajax post request to the API. return `${m.format('x').slice(0, -3)}.${m.format('x').slice(-3)}`;
*
* @param heartbeat
* @param debug
*/
async sendHeartbeat(
heartbeat: SendHeartbeat,
apiKey: string,
navigationPayload: Record<string, unknown>,
): Promise<void> {
console.log('Sending Heartbeat', heartbeat);
let payload;
const loggingType = await this.getLoggingType();
// Get only the domain from the entity.
// And send that in heartbeat
if (loggingType == 'domain') {
heartbeat.url = getDomainFromUrl(heartbeat.url);
payload = await this.preparePayload(heartbeat, 'domain');
await this.sendPostRequestToApi(
{ ...payload, ...navigationPayload },
apiKey,
heartbeat.hostname,
);
}
// Send entity in heartbeat
else if (loggingType == 'url') {
payload = await this.preparePayload(heartbeat, 'url');
await this.sendPostRequestToApi(
{ ...payload, ...navigationPayload },
apiKey,
heartbeat.hostname,
);
}
} }
/** async sendHeartbeats(): Promise<void> {
* Returns a promise with logging type variable. const settings = await browser.storage.sync.get({
* apiKey: config.apiKey,
* @returns {*} apiUrl: config.apiUrl,
* @private heartbeatApiEndPoint: config.heartbeatApiEndPoint,
*/ hostname: '',
async getLoggingType(): Promise<string> {
const items = await browser.storage.sync.get({
loggingType: config.loggingType,
}); });
if (!settings.apiKey) {
await changeExtensionStatus('notSignedIn');
return;
}
return items.loggingType; const heartbeats = (await this.db?.getAll('heartbeatQueue', undefined, 50)) as
| Heartbeat[]
| undefined;
if (!heartbeats || heartbeats.length === 0) return;
await this.db?.delete(
'heartbeatQueue',
heartbeats.map((heartbeat) => heartbeat.id),
);
const userAgent = await this.getUserAgent();
try {
const request: RequestInit = {
body: JSON.stringify(
heartbeats.map((heartbeat) => {
return { ...heartbeat, userAgent };
}),
),
credentials: 'omit',
method: 'POST',
};
if (typeof settings.hostname === 'string' && settings.hostname) {
request.headers = {
'X-Machine-Name': settings.hostname,
};
}
const url = `${settings.apiUrl}${settings.heartbeatApiEndPoint}?api_key=${settings.apiKey}`;
const response = await fetch(url, request);
if (response.status === 401) {
await this.putHeartbeatsBackInQueue(heartbeats);
await changeExtensionStatus('notSignedIn');
return;
}
const data = (await response.json()) as HeartbeatsBulkResponse;
if (data.error) {
await this.putHeartbeatsBackInQueue(heartbeats);
console.error(data.error);
return;
}
if (response.status === 201) {
await Promise.all(
(data.responses ?? []).map(async (resp, respNumber) => {
if (resp[0].error) {
await this.putHeartbeatsBackInQueue(heartbeats.filter((h, i) => i === respNumber));
console.error(resp[0].error);
} else if (resp[1] === 201 && resp[0].data?.id) {
await changeExtensionStatus('allGood');
// await this.db?.delete('heartbeatQueue', resp[0].data.id);
} else {
if (resp[1] !== 400) {
await this.putHeartbeatsBackInQueue(heartbeats.filter((h, i) => i === respNumber));
}
console.error(
`Heartbeat ${resp[0].data?.id ?? respNumber} returned status: ${resp[1]}`,
);
}
return resp;
}),
);
} else {
await this.putHeartbeatsBackInQueue(heartbeats);
console.error(`Heartbeat response status: ${response.status}`);
}
} catch (err: unknown) {
console.error(err);
await this.putHeartbeatsBackInQueue(heartbeats);
}
} }
/** async putHeartbeatsBackInQueue(heartbeats: Heartbeat[]): Promise<void> {
* Creates payload for the heartbeat and returns it as JSON. await Promise.all(
* heartbeats.map(async (heartbeat) => this.db?.add('heartbeatQueue', heartbeat)),
* @param heartbeat );
* @param type }
* @param debug
* @returns {*} async getUserAgent(): Promise<string> {
* @private const os = await getOperatingSystem();
*/
async preparePayload(heartbeat: SendHeartbeat, type: string): Promise<Record<string, unknown>> {
const os = await this.getOperatingSystem();
let browserName = 'chrome'; let browserName = 'chrome';
let userAgent; let userAgent;
if (IS_FIREFOX) { if (IS_FIREFOX) {
@@ -346,96 +263,7 @@ class WakaTimeCore {
} else { } else {
userAgent = navigator.userAgent.match(/Chrome\/\S+/g)?.[0]; userAgent = navigator.userAgent.match(/Chrome\/\S+/g)?.[0];
} }
const payload: Record<string, unknown> = { return `${userAgent} ${os} ${browserName}-wakatime/${config.version}`;
entity: heartbeat.url,
time: moment().format('X'),
type: type,
user_agent: `${userAgent} ${os} ${browserName}-wakatime/${config.version}`,
};
payload.project = heartbeat.project ?? '<<LAST_PROJECT>>';
payload.branch = heartbeat.branch ?? '<<LAST_BRANCH>>';
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.
*
* @param payload
* @param method
* @returns {*}
*/
async sendPostRequestToApi(
payload: Record<string, unknown>,
apiKey = '',
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',
method: 'POST',
};
if (hostname) {
request.headers = {
'X-Machine-Name': hostname,
};
}
const response = await fetch(
`${items.apiUrl}${items.heartbeatApiEndPoint}?api_key=${apiKey}`,
request,
);
await response.json();
} catch (err: unknown) {
if (this.db) {
await this.db.add('cacheHeartbeats', payload);
}
await changeExtensionState('notSignedIn');
}
}
/**
* Sends cached heartbeats request to wakatime api
* @param requests
*/
async sendCachedHeartbeatsRequest(): Promise<void> {
const apiKey = await getApiKey();
if (!apiKey) {
return changeExtensionState('notLogging');
}
if (this.db) {
const requests = await this.db.getAll('cacheHeartbeats');
await this.db.clear('cacheHeartbeats');
const chunkSize = 50; // Create batches of max 50 request
for (let i = 0; i < requests.length; i += chunkSize) {
const chunk = requests.slice(i, i + chunkSize);
const requestsPromises: Promise<void>[] = [];
chunk.forEach((request: Record<string, unknown>) =>
requestsPromises.push(this.sendPostRequestToApi(request, apiKey)),
);
try {
await Promise.all(requestsPromises);
} catch (error: unknown) {
console.log('Error sending heartbeats');
}
}
}
} }
} }

View File

@@ -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>

View File

@@ -1,37 +1,30 @@
// Generated by https://quicktype.io export interface Heartbeat {
branch?: string | null;
export interface HeartBeatsPayload { category?: Category | null;
data: Datum[];
end: string;
start: string;
timezone: string;
}
export interface Datum {
branch: string;
category: string;
created_at: string;
cursorpos: null;
dependencies: string;
entity: string; entity: string;
id: string; id: string;
is_write: boolean; language?: string | null;
language: string; plugin?: string | null;
lineno: null; project?: string | null;
lines: number; time: string;
machine_name_id: string; type: EntityType;
project: string;
time: number;
type: string;
user_agent_id: string;
user_id: string;
} }
export interface SendHeartbeat { export enum Category {
branch?: string | null; browsing = 'browsing',
hostname: string; code_reviewing = 'code reviewing',
project?: string | null; coding = 'coding',
url: string; communicating = 'communicating',
debugging = 'debugging',
designing = 'designing',
meeting = 'meeting',
}
export enum EntityType {
app = 'app',
domain = 'domain',
file = 'file',
url = 'url',
} }
export interface ProjectDetails { export interface ProjectDetails {
@@ -42,7 +35,6 @@ export interface ProjectDetails {
project: string; project: string;
} }
export interface PostHeartbeatMessage { export type HeartbeatsBulkResponse = { error?: string; responses?: HeartbeatResponse[] };
projectDetails?: ProjectDetails;
recordHeartbeat: boolean; export type HeartbeatResponse = [{ data?: { id: string }; error?: string }, number];
}

52
src/types/sites.ts Normal file
View File

@@ -0,0 +1,52 @@
import { Category, EntityType } from './heartbeats';
export enum KnownSite {
bitbucket = 'bitbucket',
canva = 'canva',
circleci = 'circleci',
figma = 'figma',
github = 'github',
gitlab = 'gitlab',
googlemeet = 'googlemeet',
slack = 'slack',
stackoverflow = 'stackoverflow',
travisci = 'travisci',
vercel = 'vercel',
zoom = 'zoom',
}
export interface OptionalHeartbeat {
branch?: string | null;
category?: Category | null;
entity?: string;
entityType?: EntityType;
language?: string | null;
plugin?: string;
project?: string | null;
}
export type HeartbeatParser = (url: string) => OptionalHeartbeat | undefined;
export interface SiteParser {
parser: HeartbeatParser;
urls: RegExp[] | string[];
}
export type StackExchangeSiteState = 'linked_meta' | 'normal' | 'open_beta';
export type StackExchangeSiteType = 'main_site' | 'meta_site';
export type StackExchangeSite = {
aliases?: string[];
api_site_parameter: string;
audience?: string;
favicon_url: string;
high_resolution_icon_url: string;
icon_url: string;
launch_date?: number;
logo_url: string;
name: string;
site_state: StackExchangeSiteState;
site_type: StackExchangeSiteType;
site_url: string;
};

View File

@@ -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;

View File

@@ -1,6 +1,3 @@
import browser from 'webextension-polyfill';
import config from '../config/config';
export default function apiKeyInvalid(key?: string): string { export default function apiKeyInvalid(key?: string): string {
const err = 'Invalid api key... check https://wakatime.com/settings for your key'; const err = 'Invalid api key... check https://wakatime.com/settings for your key';
if (!key) return err; if (!key) return err;
@@ -11,11 +8,3 @@ export default function apiKeyInvalid(key?: string): string {
if (!re.test(key)) return err; if (!re.test(key)) return err;
return ''; return '';
} }
export async function getApiKey(): Promise<string> {
const storage = await browser.storage.sync.get({
apiKey: config.apiKey,
});
const apiKey = storage.apiKey as string;
return apiKey;
}

View File

@@ -1,30 +0,0 @@
import browser from 'webextension-polyfill';
import config from '../config/config';
import { IS_FIREFOX } from '.';
type ColorIconTypes = 'gray' | 'red' | 'white' | '';
/**
* It changes the extension icon color.
*/
export default async function changeExtensionIcon(color?: ColorIconTypes): Promise<void> {
let path;
if (color) {
path = `./graphics/wakatime-logo-38-${color}.png`;
} else {
const { theme } = await browser.storage.sync.get({
theme: config.theme,
});
path =
theme === config.theme
? './graphics/wakatime-logo-38.png'
: './graphics/wakatime-logo-38-white.png';
}
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (IS_FIREFOX && browser.browserAction) {
await browser.browserAction.setIcon({ path: path }); // Support for FF with manifest V2
} else if ((browser.action as browser.Action.Static | undefined) !== undefined) {
await browser.action.setIcon({ path: path }); // Support for Chrome with manifest V3
}
}

View File

@@ -1,35 +0,0 @@
import browser from 'webextension-polyfill';
import config, { ApiStates } from '../config/config';
import changeExtensionIcon from './changeExtensionIcon';
import changeExtensionTooltip from './changeExtensionTooltip';
/**
* Sets the current state of the extension.
*/
export default async function changeExtensionState(state: ApiStates): Promise<void> {
switch (state) {
case 'allGood':
await changeExtensionIcon(config.colors.allGood);
await changeExtensionTooltip(config.tooltips.allGood);
break;
case 'notLogging':
await changeExtensionIcon(config.colors.notLogging);
await changeExtensionTooltip(config.tooltips.notLogging);
break;
case 'notSignedIn':
await changeExtensionIcon(config.colors.notSignedIn);
await changeExtensionTooltip(config.tooltips.notSignedIn);
break;
case 'blacklisted':
await changeExtensionIcon(config.colors.notLogging);
await changeExtensionTooltip(config.tooltips.blacklisted);
break;
case 'whitelisted':
await changeExtensionIcon(config.colors.notLogging);
await changeExtensionTooltip(config.tooltips.whitelisted);
break;
default:
break;
}
await browser.storage.sync.set({ extensionState: state });
}

View File

@@ -0,0 +1,76 @@
import browser from 'webextension-polyfill';
import config, { ExtensionStatus } from '../config/config';
import { IS_FIREFOX } from './operatingSystem';
type ColorIconTypes = 'gray' | 'red' | 'white' | '';
/**
* Sets status of the extension.
*/
export async function changeExtensionStatus(status: ExtensionStatus): Promise<void> {
switch (status) {
case 'allGood':
await changeExtensionIcon(config.colors.allGood);
await changeExtensionTooltip(config.tooltips.allGood);
break;
case 'trackingDisabled':
await changeExtensionIcon(config.colors.trackingDisabled);
await changeExtensionTooltip(config.tooltips.trackingDisabled);
break;
case 'notSignedIn':
await changeExtensionIcon(config.colors.notSignedIn);
await changeExtensionTooltip(config.tooltips.notSignedIn);
break;
case 'ignored':
await changeExtensionIcon(config.colors.trackingDisabled);
await changeExtensionTooltip(config.tooltips.ignored);
break;
default:
break;
}
await browser.storage.sync.set({ extensionStatus: status });
}
/**
* Changes the extension icon color.
*/
export async function changeExtensionIcon(color?: ColorIconTypes): Promise<void> {
let path;
if (color) {
path = `./graphics/wakatime-logo-38-${color}.png`;
} else {
const { theme } = await browser.storage.sync.get({
theme: config.theme,
});
path =
theme === config.theme
? './graphics/wakatime-logo-38.png'
: './graphics/wakatime-logo-38-white.png';
}
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (IS_FIREFOX && browser.browserAction) {
await browser.browserAction.setIcon({ path: path }); // Support for FF with manifest V2
} else if ((browser.action as browser.Action.Static | undefined) !== undefined) {
await browser.action.setIcon({ path: path }); // Support for Chrome with manifest V3
}
}
/**
* It changes the extension title
*
*/
export default async function changeExtensionTooltip(text: string): Promise<void> {
if (text === '') {
text = config.name;
} else {
text = `${config.name} - ${text}`;
}
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (IS_FIREFOX && browser.browserAction) {
await browser.browserAction.setTitle({ title: text }); // Support for FF with manifest V2
} else if ((browser.action as browser.Action.Static | undefined) !== undefined) {
await browser.action.setTitle({ title: text }); // Support for Chrome with manifest V3
}
}

View File

@@ -1,22 +0,0 @@
import browser from 'webextension-polyfill';
import config from '../config/config';
import { IS_FIREFOX } from '.';
/**
* It changes the extension title
*
*/
export default async function changeExtensionTooltip(text: string): Promise<void> {
if (text === '') {
text = config.name;
} else {
text = `${config.name} - ${text}`;
}
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (IS_FIREFOX && browser.browserAction) {
await browser.browserAction.setTitle({ title: text }); // Support for FF with manifest V2
} else if ((browser.action as browser.Action.Static | undefined) !== undefined) {
await browser.action.setTitle({ title: text }); // Support for Chrome with manifest V3
}
}

View File

@@ -1,162 +0,0 @@
import { parse } from 'node-html-parser';
export const IS_EDGE = navigator.userAgent.includes('Edg');
export const IS_FIREFOX = navigator.userAgent.includes('Firefox');
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/];
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;
};

16
src/utils/logging.ts Normal file
View 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;
};

View File

@@ -0,0 +1,11 @@
export const IS_EDGE = navigator.userAgent.includes('Edg');
export const IS_FIREFOX = navigator.userAgent.includes('Firefox');
export const IS_CHROME = IS_EDGE === false && IS_FIREFOX === false;
export const getOperatingSystem = (): Promise<string> => {
return new Promise((resolve) => {
chrome.runtime.getPlatformInfo(function (info) {
resolve(`${info.os}_${info.arch}`);
});
});
};

75
src/utils/settings.ts Normal file
View File

@@ -0,0 +1,75 @@
import browser from 'webextension-polyfill';
import config, { ExtensionStatus, LoggingStyle, LoggingType, Theme } from '../config/config';
export interface Settings {
allowList: string[];
apiKey: string;
apiUrl: string;
denyList: string[];
extensionStatus: ExtensionStatus;
hostname: string;
loggingEnabled: boolean;
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,
extensionStatus: settings.extensionStatus,
hostname: settings.hostname,
loggingEnabled: settings.loggingEnabled,
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);
};

372
src/utils/sites.ts Normal file
View File

@@ -0,0 +1,372 @@
import { Category, EntityType } from '../types/heartbeats';
import {
HeartbeatParser,
KnownSite,
OptionalHeartbeat,
SiteParser,
StackExchangeSite,
} from '../types/sites';
import { STACKEXCHANGE_SITES } from './stackexchange-sites';
const githubLanguage = (): string | undefined => {
const embedData = document.querySelector(
'script[data-target="react-app.embeddedData"]',
)?.textContent;
if (embedData) {
try {
const data = JSON.parse(embedData) as { payload?: { blob?: { language?: string } } };
if (data.payload?.blob?.language) return data.payload.blob.language;
} catch (e: unknown) {
console.error('Failed to parse GitHub language', e);
}
}
const files = Array.from(
document.querySelectorAll('div[data-details-container-group="file"]').values(),
);
const languages = files
.sort((a, b) => {
const aSize =
a
.querySelector('.file-info')
?.querySelector('.sr-only')
?.textContent?.trim()
.split(':')[1]
.trim()
.split(' ')[0]
.replace(',', '')
.replace('.', '')
.replace('k', '000')
.replace('M', '000000') ?? 0;
const bSize =
b
.querySelector('.file-info')
?.querySelector('.sr-only')
?.textContent?.trim()
.split(':')[1]
.trim()
.split(' ')[0]
.replace(',', '')
.replace('.', '')
.replace('k', '000')
.replace('M', '000000') ?? 0;
return Number(bSize) - Number(aSize);
})
.map((div) => div.getAttribute('data-tagsearch-lang'))
.filter(Boolean) as string[];
return languages[0];
};
const GitHub: HeartbeatParser = (url: string) => {
const { hostname } = new URL(url);
const match = url.match(/(?<=github\.(?:com|dev)\/[^/]+\/)([^/?#]+)/);
if (!match) return;
if (hostname.endsWith('.dev')) {
return {
project: match[0],
};
}
const body = document.getElementsByTagName('body').item(0);
if (!body) return;
const repo = body
.querySelector('meta[name=octolytics-dimension-repository_nwo]')
?.getAttribute('content');
if (repo?.split('/')[1] !== match[0]) return;
// TODO: parse language associated with this repo from the DOM
// TODO: parse branch associated with the PR url from the DOM
const re = new RegExp(/github.com\/[^/]+\/[^/]+\/pull\/\d+\/files/);
const category: Category | undefined = re.test(url) ? Category.code_reviewing : undefined;
return {
category,
language: githubLanguage(),
project: match[0],
};
};
const GitLab: HeartbeatParser = (url: string) => {
const match = url.match(/(?<=gitlab\.com\/[^/]+\/)([^/?#]+)/);
if (!match) return;
const repoName = document.querySelector('body')?.getAttribute('data-project-full-path');
if (!repoName || repoName.split('/')[1] !== match[0]) return;
return {
project: match[0],
};
};
const BitBucket: HeartbeatParser = (url: string) => {
const match = url.match(/(?<=bitbucket\.org\/[^/]+\/)([^/?#]+)/);
if (!match) return;
// this regex extracts the project name from the title
// eg. title: jhondoe / my-test-repo — Bitbucket
const match2 = document.querySelector('title')?.textContent?.match(/(?<=\/\s)([^/\s]+)(?=\s—)/);
if (!match2 || match2[0] !== match[0]) return;
return {
project: match[0],
};
};
const TravisCI: HeartbeatParser = (url: string) => {
const match = url.match(/(?<=app\.travis-ci\.com\/[^/]+\/[^/]+\/)([^/?#]+)/);
if (!match) return;
const projectName = document.querySelector('#ember737')?.textContent;
if (projectName !== match[0]) return;
return {
project: match[0],
};
};
const CircleCI: HeartbeatParser = (url: string) => {
const projectPageMatch = url.match(
/(?<=app\.circleci\.com\/projects\/[^/]+\/[^/]+\/[^/]+\/)([^/?#]+)/,
);
if (projectPageMatch) {
const seconndBreadcrumbLabel = document.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 = document.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 { project: projectPageMatch[0] };
}
}
const settingsPageMatch = url.match(
/(?<=app\.circleci\.com\/settings\/project\/[^/]+\/[^/]+\/)([^/?#]+)/,
);
if (settingsPageMatch) {
const pageTitle = document.querySelector(
'#__next > div > div:nth-child(1) > header > div > div:nth-child(2) > h1',
)?.textContent;
const pageSubtitle = document.querySelector(
'#__next > div > div:nth-child(1) > header > div > div:nth-child(2) > div',
)?.textContent;
if (pageTitle === 'Project Settings' && pageSubtitle === settingsPageMatch[0]) {
return { project: settingsPageMatch[0] };
}
}
return undefined;
};
const Vercel: HeartbeatParser = (url: string) => {
const match = url.match(/(?<=vercel\.com\/[^/]+\/)([^/?#]+)/);
if (!match) return;
// this regex extracts the project name from the title
// eg. title: test-website - Overview Vercel
const match2 = document.querySelector('title')?.textContent?.match(/^[^\s]+(?=\s-\s)/);
if (!match2 || match2[0] !== match[0]) return;
return { project: match[0] };
};
const StackOverflow: HeartbeatParser = (_url: string) => {
const tags = Array.from(document.querySelectorAll('.post-tag').values())
.map((el) => el.textContent)
.filter(Boolean) as string[];
if (tags.length === 0) return;
const languages = Array.from(document.querySelectorAll('code[data-highlighted="yes"]').values())
.map((code) => {
const cls = Array.from(code.classList.values()).find((c) => c.startsWith('language-'));
return cls?.substring('language-'.length);
})
.filter(Boolean) as string[];
for (const lang of languages) {
if (tags.includes(lang)) {
return { language: lang };
}
}
return undefined;
};
const Canva: HeartbeatParser = (_url: string): OptionalHeartbeat | undefined => {
const projectName = (document.head.querySelector('meta[property="og:title"]') as HTMLMetaElement)
.content;
if (!projectName) return;
// make sure the page title matches the design input element's value, meaning this is a design file
const canvaProjectInput = Array.from(
document.querySelector('nav')?.querySelectorAll('input')?.values() ?? [],
).find((inp) => inp.value === projectName);
if (!canvaProjectInput) return;
return {
category: Category.designing,
language: 'Image (svg)',
plugin: 'Canva',
project: projectName,
};
};
const Figma: HeartbeatParser = (_url: string): OptionalHeartbeat | undefined => {
const figmaProject = document.getElementsByClassName('gpu-view-content');
if (figmaProject.length === 0) return;
const project = (document.querySelector('span[data-testid="filename"]') as HTMLElement).innerText;
return {
category: Category.designing,
language: 'Image (svg)',
plugin: 'Figma',
project,
};
};
const GoogleMeet: HeartbeatParser = (_url: string): OptionalHeartbeat | undefined => {
const meetId = document.querySelector('[data-meeting-title]')?.getAttribute('data-meeting-title');
if (!meetId) return;
return {
category: Category.meeting,
plugin: 'Google Meet',
project: meetId,
};
};
const Slack: HeartbeatParser = (_url: string): OptionalHeartbeat | undefined => {
const title = document.querySelector('title')?.textContent?.split(' - ');
if (!title || title.length < 3 || title[-1] !== 'Slack') {
return {
category: Category.communicating,
plugin: 'Slack',
};
}
const entity = title[0];
const project = title[1];
return {
category: Category.communicating,
entity,
entityType: EntityType.app,
plugin: 'Slack',
project,
};
};
const Zoom: HeartbeatParser = (_url: string): OptionalHeartbeat | undefined => {
const entity = document.querySelector('title')?.textContent;
return {
category: Category.communicating,
entity: entity ?? undefined,
entityType: entity ? EntityType.app : undefined,
plugin: 'Zoom',
};
};
const _normalizeUrl = (url?: string | null) => {
if (!url) {
return '';
}
if (url.startsWith('http://')) {
url = url.substring('http://'.length);
}
if (url.startsWith('https://')) {
url = url.substring('https://'.length);
}
if (url.startsWith('www.')) {
url = url.substring('www.'.length);
}
if (url.endsWith('/')) {
url = url.substring(0, url.length - 1);
}
return url;
};
const stackExchangeDomains = (STACKEXCHANGE_SITES as StackExchangeSite[]).map((site) => {
return _normalizeUrl(site.site_url);
});
const SITES: Record<KnownSite, SiteParser> = {
bitbucket: {
parser: BitBucket,
urls: [/^https?:\/\/(.+\.)?bitbucket.org\//],
},
canva: {
parser: Canva,
urls: ['canva.com'],
},
circleci: {
parser: CircleCI,
urls: [/^https?:\/\/(.+\.)?circleci.com\//],
},
figma: {
parser: Figma,
urls: ['figma.com'],
},
github: {
parser: GitHub,
urls: [
/^https?:\/\/(.+\.)?github.com\//,
/^https?:\/\/(.+\.)?github.dev\//,
/^https?:\/\/(.+\.)?github.blog\//,
/^https?:\/\/(.+\.)?github.io\//,
/^https?:\/\/(.+\.)?github.community\//,
// /^https?:\/\/(.+\.)?ghcr.io\//,
// /^https?:\/\/(.+\.)?githubapp.com\//,
// /^https?:\/\/(.+\.)?githubassets.com\//,
// /^https?:\/\/(.+\.)?githubusercontent.com\//,
// /^https?:\/\/(.+\.)?githubnext.com\//,
],
},
gitlab: {
parser: GitLab,
urls: [/^https?:\/\/(.+\.)?gitlab.com\//],
},
googlemeet: {
parser: GoogleMeet,
urls: [/^https?:\/\/meet.google.com\//],
},
slack: {
parser: Slack,
urls: [/^https:\/\/app.slack.com\/client\//],
},
stackoverflow: {
parser: StackOverflow,
urls: stackExchangeDomains,
},
travisci: {
parser: TravisCI,
urls: [/^https?:\/\/(.+\.)?travis-ci.com\//],
},
vercel: {
parser: Vercel,
urls: [/^https?:\/\/(.+\.)?vercel.com\//],
},
zoom: {
parser: Zoom,
urls: [/^https:\/\/(.+\.)?zoom.us\/[^?]+\/join/],
},
};
const match = (url: string, pattern: RegExp | string): boolean => {
if (typeof pattern === 'string') {
return _normalizeUrl(url).startsWith(_normalizeUrl(pattern));
}
return pattern.test(url);
};
export const getSite = (url: string): SiteParser | undefined => {
return Object.values(SITES).find((site) => {
return site.urls.some((re) => match(url, re));
});
};

File diff suppressed because it is too large Load Diff

View File

@@ -1,10 +1,30 @@
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 changeExtensionState from './changeExtensionState'; import { ApiKeyPayload, AxiosUserResponse, User } from '../types/user';
import changeExtensionState from './changeExtensionStatus';
/**
* 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) {
@@ -13,19 +33,60 @@ 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) {
await changeExtensionState('allGood'); await changeExtensionState('allGood');
} else { } else {
await changeExtensionState('notLogging'); await changeExtensionState('trackingDisabled');
} }
} catch (err: unknown) { } catch (err: unknown) {
await changeExtensionState('notSignedIn'); await changeExtensionState('notSignedIn');
} }
}; };
/**
* 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));
@@ -60,23 +121,11 @@ export const fetchUserData = async (
if (items.loggingEnabled === true) { if (items.loggingEnabled === true) {
await changeExtensionState('allGood'); await changeExtensionState('allGood');
} else { } else {
await changeExtensionState('notLogging'); await changeExtensionState('trackingDisabled');
} }
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) {
html = await getHtmlContentByTabId(tabId);
}
await WakaTimeCore.recordHeartbeat(html);
} catch (err: unknown) { } catch (err: unknown) {
await changeExtensionState('notSignedIn'); await changeExtensionState('notSignedIn');
} }

View File

@@ -1,91 +1,64 @@
const twoMinutes = 120000; import { getSite } from './utils/sites';
interface DesignProject { const oneMinute = 60000;
category: string; const fiveMinutes = 300000;
editor: string;
language: string;
project: string;
}
const parseCanva = (): DesignProject | undefined => { /**
const projectName = (document.head.querySelector('meta[property="og:title"]') as HTMLMetaElement) * Debounces the execution of a function.
.content; *
if (!projectName) return; * @param {() => void} func - The function to debounce.
* @param {number} [timeout] - The timeout for the debounce in milliseconds.
// make sure the page title matches the design input element's value, meaning this is a design file * @param {number} [maxWaitTime] - The max time to debounce before forcing execution in milliseconds.
const canvaProjectInput = Array.from( * @returns {() => void} The debounced function.
document.querySelector('nav')?.querySelectorAll('input') ?? [], */
).find((inp) => inp.value === projectName); function debounce(func: () => void, timeout = oneMinute, maxWaitTime = fiveMinutes) {
if (!canvaProjectInput) return;
return {
category: 'designing',
editor: 'Canva',
language: 'Canva Design',
project: projectName,
};
};
const parseFigma = (): DesignProject | undefined => {
const figmaProject = document.getElementsByClassName('gpu-view-content');
if (figmaProject.length === 0) return;
const projectName = (document.querySelector('span[data-testid="filename"]') as HTMLElement)
.innerText;
return {
category: 'designing',
editor: 'Figma',
language: 'Figma Design',
project: projectName,
};
};
const getParser: {
[key: string]:
| (() => { editor: string; language: string; project: string } | undefined)
| undefined;
} = {
'www.canva.com': parseCanva,
'www.figma.com': parseFigma,
};
const init = async () => {
const { hostname } = document.location;
const projectDetails = getParser[hostname]?.();
if (projectDetails) {
chrome.runtime.sendMessage({ projectDetails, recordHeartbeat: true });
}
};
function debounce(func: () => void, timeout = twoMinutes) {
let timer: NodeJS.Timeout | undefined; let timer: NodeJS.Timeout | undefined;
return () => { let lastExecutionTime: number | undefined;
if (timer) { return (...args: unknown[]) => {
return; clearTimeout(timer);
if (lastExecutionTime && lastExecutionTime + maxWaitTime < Date.now()) {
lastExecutionTime = Date.now();
func(...(args as []));
} }
func();
timer = setTimeout(() => { timer = setTimeout(() => {
clearTimeout(timer); lastExecutionTime = Date.now();
timer = undefined; func(...(args as []));
}, timeout); }, timeout);
}; };
} }
document.body.addEventListener( const sendHeartbeat = debounce(async () => {
'click', chrome.runtime.sendMessage({ task: 'handleActivity' });
debounce(() => init()),
true,
);
document.body.addEventListener(
'keypress',
debounce(() => init()),
true,
);
chrome.runtime.onMessage.addListener((request: { message: string }, sender, sendResponse) => {
if (request.message === 'get_html') {
sendResponse({ html: document.documentElement.outerHTML });
}
}); });
chrome.runtime.onMessage.addListener(
(request: { task: string; url: string }, sender, sendResponse) => {
if (request.task === 'getHeartbeatFromPage') {
const site = getSite(request.url);
if (!site) {
sendResponse({ heartbeat: undefined });
return;
}
sendResponse({ heartbeat: site.parser(request.url) });
}
},
);
document.body.addEventListener('click', sendHeartbeat, true);
document.body.addEventListener('keypress', sendHeartbeat, true);
const checkIfInAMeeting = () => {
const isActiveMeeting = !!document.querySelector('[data-meeting-title]');
if (isActiveMeeting) {
sendHeartbeat();
}
setTimeout(checkIfInAMeeting, oneMinute);
};
// Google Meet
if (window.location.href.startsWith('https://meet.google.com/')) {
checkIfInAMeeting();
}

View File

@@ -1,20 +0,0 @@
import chai from 'chai';
import changeExtensionIcon from '../../src/utils/changeExtensionIcon';
const expect = chai.expect;
jest.mock('webextension-polyfill', () => {
return {
runtime: {
getManifest: () => {
return { version: 'test-version' };
},
},
};
});
describe('changeExtensionIcon', function () {
it('should be a function', function () {
expect(changeExtensionIcon).to.be.a('function');
});
});

View File

@@ -1,20 +0,0 @@
import chai from 'chai';
import changeExtensionState from '../../src/utils/changeExtensionState';
const expect = chai.expect;
jest.mock('webextension-polyfill', () => {
return {
runtime: {
getManifest: () => {
return { version: 'test-version' };
},
},
};
});
describe('changeExtensionState', function () {
it('should be a function', function () {
expect(changeExtensionState).to.be.a('function');
});
});

View File

@@ -1,26 +0,0 @@
import chai from 'chai';
import changeExtensionTooltip from '../../src/utils/changeExtensionTooltip';
const expect = chai.expect;
jest.mock('webextension-polyfill', () => {
return {
runtime: {
getManifest: () => {
return { version: 'test-version' };
},
},
};
});
describe('changeExtensionTooltip', function () {
it('should be a function', function () {
expect(changeExtensionTooltip).to.be.a('function');
});
// it('should change the extension tooltip', function() {
// changeExtensionTooltip('WakaTime');
// expect(chrome.browserAction.setTitle).toHaveBeenCalledWith({title: 'Wakatime'});
// sinon.assert.calledWithMatch(chrome.browserAction.setTitle, {title: 'WakaTime'});
// });
});

View File

@@ -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';

View File

@@ -58,7 +58,7 @@ const getConfigByBrowser = (isProd: boolean, browser: BrowserTypes): webpack.Con
new webpack.DefinePlugin({ new webpack.DefinePlugin({
['process.env.API_URL']: JSON.stringify('https://api.wakatime.com/api/v1'), ['process.env.API_URL']: JSON.stringify('https://api.wakatime.com/api/v1'),
['process.env.CURRENT_USER_API_URL']: JSON.stringify('/users/current'), ['process.env.CURRENT_USER_API_URL']: JSON.stringify('/users/current'),
['process.env.HEARTBEAT_API_URL']: JSON.stringify('/users/current/heartbeats'), ['process.env.HEARTBEAT_API_URL']: JSON.stringify('/users/current/heartbeats.bulk'),
['process.env.LOGOUT_USER_URL']: JSON.stringify('https://wakatime.com/logout'), ['process.env.LOGOUT_USER_URL']: JSON.stringify('https://wakatime.com/logout'),
['process.env.NODE_ENV']: JSON.stringify(isProd ? 'production' : 'development'), ['process.env.NODE_ENV']: JSON.stringify(isProd ? 'production' : 'development'),
['process.env.SUMMARIES_API_URL']: JSON.stringify('/users/current/summaries'), ['process.env.SUMMARIES_API_URL']: JSON.stringify('/users/current/summaries'),