Merge pull request #265 from wakatime/feature/google-meet-support
Feature/google meet support
This commit is contained in:
54
package-lock.json
generated
54
package-lock.json
generated
@@ -23,6 +23,7 @@
|
||||
"react-redux": "^8.0.5",
|
||||
"react-transition-group": "^4.4.5",
|
||||
"redux-logger": "^4.0.0",
|
||||
"uuid": "^10.0.0",
|
||||
"webextension-polyfill": "^0.10.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -49,6 +50,7 @@
|
||||
"@types/redux-logger": "^3.0.9",
|
||||
"@types/shelljs": "^0.8.8",
|
||||
"@types/sinon-chrome": "^2.2.11",
|
||||
"@types/uuid": "^10.0.0",
|
||||
"@types/wait-on": "^5.2.0",
|
||||
"@types/webextension-polyfill": "^0.10.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",
|
||||
"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": {
|
||||
"version": "5.3.1",
|
||||
"resolved": "https://registry.npmjs.org/@types/wait-on/-/wait-on-5.3.1.tgz",
|
||||
@@ -18779,6 +18788,17 @@
|
||||
"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": {
|
||||
"version": "1.0.6",
|
||||
"resolved": "https://registry.npmjs.org/require-at/-/require-at-1.0.6.tgz",
|
||||
@@ -21388,13 +21408,16 @@
|
||||
"dev": true
|
||||
},
|
||||
"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,
|
||||
"version": "10.0.0",
|
||||
"resolved": "https://registry.npmjs.org/uuid/-/uuid-10.0.0.tgz",
|
||||
"integrity": "sha512-8XkAphELsDnEGrDxUOHB3RGvXz6TeuYSGEZBOjtTtPm2lwhGBjLgOzLHB63IUWfBpNucQjND6d3AOudO+H3RWQ==",
|
||||
"funding": [
|
||||
"https://github.com/sponsors/broofa",
|
||||
"https://github.com/sponsors/ctavan"
|
||||
],
|
||||
"license": "MIT",
|
||||
"bin": {
|
||||
"uuid": "bin/uuid"
|
||||
"uuid": "dist/bin/uuid"
|
||||
}
|
||||
},
|
||||
"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",
|
||||
"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": {
|
||||
"version": "5.3.1",
|
||||
"resolved": "https://registry.npmjs.org/@types/wait-on/-/wait-on-5.3.1.tgz",
|
||||
@@ -36628,6 +36657,12 @@
|
||||
"psl": "^1.1.28",
|
||||
"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
|
||||
},
|
||||
"uuid": {
|
||||
"version": "3.4.0",
|
||||
"resolved": "https://registry.npmjs.org/uuid/-/uuid-3.4.0.tgz",
|
||||
"integrity": "sha512-HjSDRw6gZE5JMggctHBcjVak08+KEVhSIiDzFnT9S9aegmp85S/bReBVTb4QTFaRNptJ9kuYaNhnbNEOkbKb/A==",
|
||||
"dev": true
|
||||
"version": "10.0.0",
|
||||
"resolved": "https://registry.npmjs.org/uuid/-/uuid-10.0.0.tgz",
|
||||
"integrity": "sha512-8XkAphELsDnEGrDxUOHB3RGvXz6TeuYSGEZBOjtTtPm2lwhGBjLgOzLHB63IUWfBpNucQjND6d3AOudO+H3RWQ=="
|
||||
},
|
||||
"v8-compile-cache": {
|
||||
"version": "2.3.0",
|
||||
|
||||
@@ -44,6 +44,7 @@
|
||||
"react-redux": "^8.0.5",
|
||||
"react-transition-group": "^4.4.5",
|
||||
"redux-logger": "^4.0.0",
|
||||
"uuid": "^10.0.0",
|
||||
"webextension-polyfill": "^0.10.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -70,6 +71,7 @@
|
||||
"@types/redux-logger": "^3.0.9",
|
||||
"@types/shelljs": "^0.8.8",
|
||||
"@types/sinon-chrome": "^2.2.11",
|
||||
"@types/uuid": "^10.0.0",
|
||||
"@types/wait-on": "^5.2.0",
|
||||
"@types/webextension-polyfill": "^0.10.0",
|
||||
"@typescript-eslint/eslint-plugin": "^4.33.0",
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
import browser from 'webextension-polyfill';
|
||||
import WakaTimeCore from './core/WakaTimeCore';
|
||||
import { PostHeartbeatMessage } from './types/heartbeats';
|
||||
import { getHtmlContentByTabId } from './utils';
|
||||
|
||||
// Add a listener to resolve alarms
|
||||
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,
|
||||
// if so then procedd to send these payload to wakatime api
|
||||
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.
|
||||
*/
|
||||
browser.tabs.onActivated.addListener(async (activeInfo) => {
|
||||
console.log('recording a heartbeat - active tab changed');
|
||||
const html = await getHtmlContentByTabId(activeInfo.tabId);
|
||||
await WakaTimeCore.recordHeartbeat(html);
|
||||
await WakaTimeCore.handleActivity(activeInfo.tabId);
|
||||
});
|
||||
|
||||
/**
|
||||
@@ -34,18 +30,15 @@ browser.tabs.onActivated.addListener(async (activeInfo) => {
|
||||
*/
|
||||
browser.windows.onFocusChanged.addListener(async (windowId) => {
|
||||
if (windowId != browser.windows.WINDOW_ID_NONE) {
|
||||
console.log('recording a heartbeat - active window changed');
|
||||
const tabs: browser.Tabs.Tab[] = await browser.tabs.query({
|
||||
active: true,
|
||||
currentWindow: true,
|
||||
});
|
||||
|
||||
let html = '';
|
||||
const tabId = tabs[0]?.id;
|
||||
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 (tabId == tabs[0]?.id) {
|
||||
const html = await getHtmlContentByTabId(tabId);
|
||||
await WakaTimeCore.recordHeartbeat(html);
|
||||
await WakaTimeCore.handleActivity(tabs[0].id);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -76,12 +68,10 @@ self.addEventListener('activate', async () => {
|
||||
await WakaTimeCore.createDB();
|
||||
});
|
||||
|
||||
browser.runtime.onMessage.addListener(async (request: PostHeartbeatMessage, sender) => {
|
||||
if (request.recordHeartbeat === true) {
|
||||
if (sender.tab?.id) {
|
||||
const html = await getHtmlContentByTabId(sender.tab.id);
|
||||
await WakaTimeCore.recordHeartbeat(html, request.projectDetails);
|
||||
}
|
||||
browser.runtime.onMessage.addListener(async (request: { task: string }, sender) => {
|
||||
if (request.task === 'handleActivity') {
|
||||
if (!sender.tab?.id) return;
|
||||
await WakaTimeCore.handleActivity(sender.tab.id);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ import { configLogout, setLoggingEnabled } from '../reducers/configReducer';
|
||||
import { userLogout } from '../reducers/currentUser';
|
||||
import { ReduxSelector } from '../types/store';
|
||||
import { User } from '../types/user';
|
||||
import changeExtensionState from '../utils/changeExtensionState';
|
||||
import changeExtensionState from '../utils/changeExtensionStatus';
|
||||
|
||||
export interface MainListProps {
|
||||
loggingEnabled: boolean;
|
||||
@@ -40,7 +40,7 @@ export default function MainList({
|
||||
const disableLogging = async (): Promise<void> => {
|
||||
dispatch(setLoggingEnabled(false));
|
||||
await browser.storage.sync.set({ loggingEnabled: false });
|
||||
await changeExtensionState('notLogging');
|
||||
await changeExtensionState('trackingDisabled');
|
||||
};
|
||||
|
||||
return (
|
||||
|
||||
@@ -1,78 +1,43 @@
|
||||
import React, { useEffect, useRef, useState } from 'react';
|
||||
import config, { SuccessOrFailType } from '../config/config';
|
||||
import { IS_CHROME } from '../utils';
|
||||
import apiKeyInvalid from '../utils/apiKey';
|
||||
import { IS_CHROME } from '../utils/operatingSystem';
|
||||
import { getSettings, saveSettings, Settings } from '../utils/settings';
|
||||
import { logUserIn } from '../utils/user';
|
||||
import SitesList from './SitesList';
|
||||
|
||||
interface State {
|
||||
interface State extends Settings {
|
||||
alertText: string;
|
||||
alertType: SuccessOrFailType;
|
||||
apiKey: string;
|
||||
apiUrl: string;
|
||||
blacklist: string;
|
||||
hostname: string;
|
||||
loading: boolean;
|
||||
loggingStyle: string;
|
||||
loggingType: string;
|
||||
socialMediaSites: string[];
|
||||
theme: string;
|
||||
trackSocialMedia: boolean;
|
||||
whitelist: string;
|
||||
}
|
||||
|
||||
export default function Options(): JSX.Element {
|
||||
const [state, setState] = useState<State>({
|
||||
alertText: config.alert.success.text,
|
||||
alertType: config.alert.success.type,
|
||||
allowList: [],
|
||||
apiKey: '',
|
||||
apiUrl: config.apiUrl,
|
||||
blacklist: '',
|
||||
denyList: [],
|
||||
extensionStatus: 'allGood',
|
||||
hostname: '',
|
||||
loading: false,
|
||||
loggingEnabled: true,
|
||||
loggingStyle: config.loggingStyle,
|
||||
loggingType: config.loggingType,
|
||||
socialMediaSites: config.socialMediaSites,
|
||||
theme: config.theme,
|
||||
trackSocialMedia: config.trackSocialMedia,
|
||||
whitelist: '',
|
||||
});
|
||||
|
||||
const loggingStyleRef = useRef(null);
|
||||
|
||||
const restoreSettings = async (): Promise<void> => {
|
||||
const items = await browser.storage.sync.get({
|
||||
apiKey: config.apiKey,
|
||||
apiUrl: config.apiUrl,
|
||||
blacklist: '',
|
||||
hostname: config.hostname,
|
||||
loggingStyle: config.loggingStyle,
|
||||
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');
|
||||
}
|
||||
|
||||
const settings = await getSettings();
|
||||
setState({
|
||||
...state,
|
||||
apiKey: items.apiKey as string,
|
||||
apiUrl: items.apiUrl as string,
|
||||
blacklist: items.blacklist as string,
|
||||
hostname: items.hostname as string,
|
||||
loggingStyle: items.loggingStyle as string,
|
||||
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,
|
||||
...settings,
|
||||
});
|
||||
};
|
||||
|
||||
@@ -83,68 +48,62 @@ export default function Options(): JSX.Element {
|
||||
const handleSubmit = async () => {
|
||||
if (state.loading) return;
|
||||
setState({ ...state, loading: true });
|
||||
|
||||
const apiKey = state.apiKey;
|
||||
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);
|
||||
if (state.apiUrl.endsWith('/')) {
|
||||
state.apiUrl = state.apiUrl.slice(0, -1);
|
||||
}
|
||||
|
||||
// Sync options with google storage.
|
||||
await browser.storage.sync.set({
|
||||
apiKey,
|
||||
apiUrl,
|
||||
blacklist,
|
||||
hostname,
|
||||
loggingStyle,
|
||||
loggingType,
|
||||
socialMediaSites,
|
||||
theme,
|
||||
trackSocialMedia,
|
||||
whitelist,
|
||||
});
|
||||
|
||||
// Set state to be newly entered values.
|
||||
setState({
|
||||
...state,
|
||||
apiKey,
|
||||
apiUrl,
|
||||
blacklist,
|
||||
hostname,
|
||||
loggingStyle,
|
||||
loggingType,
|
||||
socialMediaSites,
|
||||
theme,
|
||||
trackSocialMedia,
|
||||
whitelist,
|
||||
await saveSettings({
|
||||
allowList: state.allowList,
|
||||
apiKey: state.apiKey,
|
||||
apiUrl: state.apiUrl,
|
||||
denyList: state.denyList,
|
||||
extensionStatus: state.extensionStatus,
|
||||
hostname: state.hostname,
|
||||
loggingEnabled: state.loggingEnabled,
|
||||
loggingStyle: state.loggingStyle,
|
||||
loggingType: state.loggingType,
|
||||
socialMediaSites: state.socialMediaSites,
|
||||
theme: state.theme,
|
||||
trackSocialMedia: state.trackSocialMedia,
|
||||
});
|
||||
setState(state);
|
||||
await logUserIn(state.apiKey);
|
||||
if (IS_CHROME) {
|
||||
window.close();
|
||||
}
|
||||
};
|
||||
|
||||
const updateBlacklistState = (sites: string) => {
|
||||
const updateDenyListState = (sites: string) => {
|
||||
setState({
|
||||
...state,
|
||||
blacklist: sites,
|
||||
denyList: sites.trim().split('\n'),
|
||||
});
|
||||
};
|
||||
|
||||
const updateWhitelistState = (sites: string) => {
|
||||
const updateAllowListState = (sites: string) => {
|
||||
setState({
|
||||
...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 () {
|
||||
if (state.loggingStyle == 'blacklist') {
|
||||
// TODO: rewrite SitesList to be structured inputs instead of textarea
|
||||
|
||||
if (state.loggingStyle == 'deny') {
|
||||
return (
|
||||
<SitesList
|
||||
handleChange={updateBlacklistState}
|
||||
label="Blacklist"
|
||||
sites={state.blacklist}
|
||||
handleChange={updateDenyListState}
|
||||
label="Exclude"
|
||||
sites={state.denyList.join('\n')}
|
||||
helpText="Sites that you don't want to show in your reports."
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<SitesList
|
||||
handleChange={updateWhitelistState}
|
||||
label="Whitelist"
|
||||
sites={state.whitelist}
|
||||
handleChange={updateAllowListState}
|
||||
label="Include"
|
||||
sites={state.allowList.join('\n')}
|
||||
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 +166,10 @@ export default function Options(): JSX.Element {
|
||||
ref={loggingStyleRef}
|
||||
className="form-control"
|
||||
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="whitelist">Only whitelisted sites</option>
|
||||
<option value="denyList">All except excluded sites</option>
|
||||
<option value="allowList">Only allowed sites</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
@@ -223,7 +183,7 @@ export default function Options(): JSX.Element {
|
||||
id="loggingType"
|
||||
className="form-control"
|
||||
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="url">Entire URL</option>
|
||||
@@ -238,7 +198,7 @@ export default function Options(): JSX.Element {
|
||||
id="selectTheme"
|
||||
className="form-control"
|
||||
value={state.theme}
|
||||
onChange={(e) => setState({ ...state, theme: e.target.value })}
|
||||
onChange={(e) => updateTheme(e.target.value)}
|
||||
>
|
||||
<option value="light">Light</option>
|
||||
<option value="dark">Dark</option>
|
||||
|
||||
@@ -10,7 +10,7 @@ import NavBar from './NavBar';
|
||||
|
||||
export default function WakaTime(): JSX.Element {
|
||||
const dispatch = useDispatch();
|
||||
const [extensionState, setExtensionState] = useState('');
|
||||
const [extensionStatus, setExtensionStatus] = useState('');
|
||||
|
||||
const {
|
||||
apiKey: apiKeyFromRedux,
|
||||
@@ -21,8 +21,8 @@ export default function WakaTime(): JSX.Element {
|
||||
useEffect(() => {
|
||||
const fetchData = async () => {
|
||||
await fetchUserData(apiKeyFromRedux, dispatch);
|
||||
const items = await browser.storage.sync.get({ extensionState: '' });
|
||||
setExtensionState(items.extensionState as string);
|
||||
const items = await browser.storage.sync.get({ extensionStatus: '' });
|
||||
setExtensionStatus(items.extensionStatus as string);
|
||||
};
|
||||
void fetchData();
|
||||
}, []);
|
||||
@@ -32,7 +32,7 @@ export default function WakaTime(): JSX.Element {
|
||||
return (
|
||||
<div className="py-4 px-2 pt-0">
|
||||
<NavBar />
|
||||
{isApiKeyValid && extensionState === 'notSignedIn' && (
|
||||
{isApiKeyValid && extensionStatus === 'notSignedIn' && (
|
||||
<Alert
|
||||
type={config.alert.failure.type}
|
||||
text={'Invalid API key or API url'}
|
||||
|
||||
@@ -29,8 +29,8 @@ describe('wakatime config', () => {
|
||||
"colors": {
|
||||
"allGood": "",
|
||||
"lightTheme": "white",
|
||||
"notLogging": "gray",
|
||||
"notSignedIn": "red",
|
||||
"trackingDisabled": "gray",
|
||||
},
|
||||
"currentUserApiEndPoint": "/users/current",
|
||||
"detectionIntervalInSeconds": 60,
|
||||
@@ -46,10 +46,10 @@ describe('wakatime config', () => {
|
||||
"udemy.com",
|
||||
"w3schools.com",
|
||||
],
|
||||
"heartbeatApiEndPoint": "/users/current/heartbeats",
|
||||
"heartbeatApiEndPoint": "/users/current/heartbeats.bulk",
|
||||
"hostname": "",
|
||||
"loggingEnabled": true,
|
||||
"loggingStyle": "blacklist",
|
||||
"loggingStyle": "deny",
|
||||
"loggingType": "domain",
|
||||
"logoutUserUrl": "https://wakatime.com/logout",
|
||||
"name": "WakaTime",
|
||||
@@ -71,19 +71,17 @@ describe('wakatime config', () => {
|
||||
],
|
||||
"states": [
|
||||
"allGood",
|
||||
"notLogging",
|
||||
"trackingDisabled",
|
||||
"notSignedIn",
|
||||
"blacklisted",
|
||||
"whitelisted",
|
||||
"ignored",
|
||||
],
|
||||
"summariesApiEndPoint": "/users/current/summaries",
|
||||
"theme": "light",
|
||||
"tooltips": {
|
||||
"allGood": "",
|
||||
"blacklisted": "This URL is blacklisted",
|
||||
"notLogging": "Not logging",
|
||||
"ignored": "This URL is ignored",
|
||||
"notSignedIn": "Not signed In",
|
||||
"whitelisted": "This URL is not on your whitelist",
|
||||
"trackingDisabled": "Not logging",
|
||||
},
|
||||
"trackSocialMedia": true,
|
||||
"version": "test-version",
|
||||
|
||||
@@ -3,16 +3,18 @@ import browser from 'webextension-polyfill';
|
||||
/**
|
||||
* Logging
|
||||
*/
|
||||
export type ApiStates = 'allGood' | 'notLogging' | 'notSignedIn' | 'blacklisted' | 'whitelisted';
|
||||
export type ExtensionStatus = 'allGood' | 'trackingDisabled' | 'notSignedIn' | 'ignored';
|
||||
/**
|
||||
* Supported logging style
|
||||
*/
|
||||
export type LoggingStyle = 'whitelist' | 'blacklist';
|
||||
export type LoggingStyle = 'allow' | 'deny';
|
||||
|
||||
/**
|
||||
* Logging type
|
||||
*/
|
||||
export type LoggingType = 'domain' | 'url';
|
||||
export type SuccessOrFailType = 'success' | 'danger';
|
||||
export type Theme = 'light' | 'dark';
|
||||
/**
|
||||
* Predefined alert type and text for success and failure.
|
||||
*/
|
||||
@@ -33,18 +35,17 @@ interface SuccessOrFailAlert {
|
||||
interface Colors {
|
||||
allGood: '';
|
||||
lightTheme: 'white';
|
||||
notLogging: 'gray';
|
||||
notSignedIn: 'red';
|
||||
trackingDisabled: 'gray';
|
||||
}
|
||||
/**
|
||||
* Tooltip messages
|
||||
*/
|
||||
interface Tooltips {
|
||||
allGood: string;
|
||||
blacklisted: string;
|
||||
notLogging: string;
|
||||
ignored: string;
|
||||
notSignedIn: string;
|
||||
whitelisted: string;
|
||||
trackingDisabled: string;
|
||||
}
|
||||
|
||||
export interface Config {
|
||||
@@ -89,7 +90,7 @@ export interface Config {
|
||||
name: string;
|
||||
nonTrackableSites: string[];
|
||||
socialMediaSites: string[];
|
||||
states: ApiStates[];
|
||||
states: ExtensionStatus[];
|
||||
/**
|
||||
* Get stats from the wakatime api
|
||||
*/
|
||||
@@ -97,7 +98,7 @@ export interface Config {
|
||||
/**
|
||||
* Options for theme
|
||||
*/
|
||||
theme: 'light';
|
||||
theme: Theme;
|
||||
tooltips: Tooltips;
|
||||
trackSocialMedia: boolean;
|
||||
/**
|
||||
@@ -125,8 +126,8 @@ const config: Config = {
|
||||
colors: {
|
||||
allGood: '',
|
||||
lightTheme: 'white',
|
||||
notLogging: 'gray',
|
||||
notSignedIn: 'red',
|
||||
trackingDisabled: 'gray',
|
||||
},
|
||||
|
||||
currentUserApiEndPoint: process.env.CURRENT_USER_API_URL ?? '/users/current',
|
||||
@@ -146,13 +147,13 @@ const config: Config = {
|
||||
'w3schools.com',
|
||||
],
|
||||
|
||||
heartbeatApiEndPoint: process.env.HEARTBEAT_API_URL ?? '/users/current/heartbeats',
|
||||
heartbeatApiEndPoint: process.env.HEARTBEAT_API_URL ?? '/users/current/heartbeats.bulk',
|
||||
|
||||
hostname: '',
|
||||
|
||||
loggingEnabled: true,
|
||||
|
||||
loggingStyle: 'blacklist',
|
||||
loggingStyle: 'deny',
|
||||
|
||||
loggingType: 'domain',
|
||||
|
||||
@@ -175,7 +176,7 @@ const config: Config = {
|
||||
'youtube.com',
|
||||
],
|
||||
|
||||
states: ['allGood', 'notLogging', 'notSignedIn', 'blacklisted', 'whitelisted'],
|
||||
states: ['allGood', 'trackingDisabled', 'notSignedIn', 'ignored'],
|
||||
|
||||
summariesApiEndPoint: process.env.SUMMARIES_API_URL ?? '/users/current/summaries',
|
||||
|
||||
@@ -183,10 +184,9 @@ const config: Config = {
|
||||
|
||||
tooltips: {
|
||||
allGood: '',
|
||||
blacklisted: 'This URL is blacklisted',
|
||||
notLogging: 'Not logging',
|
||||
ignored: 'This URL is ignored',
|
||||
notSignedIn: 'Not signed In',
|
||||
whitelisted: 'This URL is not on your whitelist',
|
||||
trackingDisabled: 'Not logging',
|
||||
},
|
||||
trackSocialMedia: true,
|
||||
|
||||
|
||||
@@ -1,21 +1,23 @@
|
||||
import { IDBPDatabase, openDB } from 'idb';
|
||||
import browser, { Tabs } from 'webextension-polyfill';
|
||||
/* eslint-disable no-fallthrough */
|
||||
/* eslint-disable default-case */
|
||||
import axios, { AxiosResponse } from 'axios';
|
||||
import { IDBPDatabase, openDB } from 'idb';
|
||||
import moment from 'moment';
|
||||
import browser, { Tabs } from 'webextension-polyfill';
|
||||
import config from '../config/config';
|
||||
import { SendHeartbeat } 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 changeExtensionState from '../utils/changeExtensionState';
|
||||
import contains from '../utils/contains';
|
||||
import { v4 as uuid4 } from 'uuid';
|
||||
import { OptionalHeartbeat } from '../types/sites';
|
||||
import { changeExtensionStatus } from '../utils/changeExtensionStatus';
|
||||
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 {
|
||||
tabsWithDevtoolsOpen: Tabs.Tab[];
|
||||
lastHeartbeat: Heartbeat | undefined;
|
||||
lastHeartbeatSentAt = 0;
|
||||
lastExtensionState: ExtensionStatus = 'allGood';
|
||||
db: IDBPDatabase | undefined;
|
||||
constructor() {
|
||||
this.tabsWithDevtoolsOpen = [];
|
||||
@@ -29,312 +31,227 @@ class WakaTimeCore {
|
||||
const dbConnection = await openDB('wakatime', 1, {
|
||||
upgrade(db, oldVersion) {
|
||||
// Create a store of objects
|
||||
const store = db.createObjectStore('cacheHeartbeats', {
|
||||
// The `time` property of the object will be the key, and be incremented automatically
|
||||
keyPath: 'time',
|
||||
const store = db.createObjectStore('heartbeatQueue', {
|
||||
keyPath: 'id',
|
||||
});
|
||||
// Switch over the oldVersion, *without breaks*, to allow the database to be incrementally upgraded.
|
||||
switch (oldVersion) {
|
||||
case 0:
|
||||
// Placeholder to execute when database is created (oldVersion is 0)
|
||||
case 1:
|
||||
// Create an index called `type` based on the `type` property of objects in the store
|
||||
store.createIndex('time', 'time');
|
||||
store.createIndex('id', 'id');
|
||||
}
|
||||
},
|
||||
});
|
||||
this.db = dbConnection;
|
||||
}
|
||||
|
||||
setTabsWithDevtoolsOpen(tabs: Tabs.Tab[]): void {
|
||||
this.tabsWithDevtoolsOpen = tabs;
|
||||
shouldSendHeartbeat(heartbeat: Heartbeat): boolean {
|
||||
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> {
|
||||
const items = await browser.storage.sync.get({
|
||||
apiUrl: config.apiUrl,
|
||||
summariesApiEndPoint: config.summariesApiEndPoint,
|
||||
});
|
||||
canSendHeartbeat(url: string, settings: Settings): boolean {
|
||||
for (const site of config.nonTrackableSites) {
|
||||
if (url.startsWith(site)) {
|
||||
// Don't send a heartbeat on sites like 'chrome://newtab/' or 'about:newtab'
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
const today = moment().format('YYYY-MM-DD');
|
||||
const summariesAxiosPayload: AxiosResponse<SummariesPayload> = await axios.get(
|
||||
`${items.apiUrl}${items.summariesApiEndPoint}`,
|
||||
{
|
||||
params: {
|
||||
api_key,
|
||||
end: today,
|
||||
start: today,
|
||||
},
|
||||
},
|
||||
);
|
||||
return summariesAxiosPayload.data.data[0].grand_total;
|
||||
}
|
||||
if (!settings.trackSocialMedia) {
|
||||
const domain = getDomain(url);
|
||||
if (
|
||||
settings.socialMediaSites.find((pattern) => {
|
||||
const re = new RegExp(pattern.replace(/\*/g, '.*'));
|
||||
return re.test(domain);
|
||||
}) !== undefined
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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`,
|
||||
if (settings.loggingStyle === 'deny') {
|
||||
return (
|
||||
settings.denyList.find((pattern) => {
|
||||
const re = new RegExp(pattern.replace(/\*/g, '.*'));
|
||||
return re.test(url);
|
||||
}) == undefined
|
||||
);
|
||||
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 (
|
||||
settings.allowList.find((pattern) => {
|
||||
const re = new RegExp(pattern.replace(/\*/g, '.*'));
|
||||
return re.test(url);
|
||||
}) !== undefined
|
||||
);
|
||||
return userPayload.data.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Depending on various factors detects the current active tab URL or domain,
|
||||
* and sends it to WakaTime for logging.
|
||||
*/
|
||||
async recordHeartbeat(html: string, payload: Record<string, unknown> = {}): Promise<void> {
|
||||
const apiKey = await getApiKey();
|
||||
if (!apiKey) {
|
||||
return changeExtensionState('notLogging');
|
||||
async handleActivity(tabId: number) {
|
||||
const settings = await getSettings();
|
||||
if (!settings.loggingEnabled) {
|
||||
await changeExtensionStatus('trackingDisabled');
|
||||
return;
|
||||
}
|
||||
const items = await browser.storage.sync.get({
|
||||
blacklist: '',
|
||||
hostname: config.hostname,
|
||||
loggingEnabled: config.loggingEnabled,
|
||||
loggingStyle: config.loggingStyle,
|
||||
socialMediaSites: config.socialMediaSites,
|
||||
trackSocialMedia: config.trackSocialMedia,
|
||||
whitelist: '',
|
||||
|
||||
const activeTab = await this.getCurrentTab(tabId);
|
||||
if (!activeTab) return;
|
||||
|
||||
const url = activeTab.url as string;
|
||||
|
||||
if (!this.canSendHeartbeat(url, settings)) {
|
||||
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) {
|
||||
await changeExtensionState('allGood');
|
||||
const activeTab = tabs[0];
|
||||
if (tabId !== activeTab.id) return;
|
||||
|
||||
let newState = '';
|
||||
// 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.`);
|
||||
}
|
||||
}
|
||||
}
|
||||
return activeTab;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an array from list using \n as delimiter
|
||||
* and checks if any element in list is contained in the url.
|
||||
* 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,
|
||||
};
|
||||
}
|
||||
async buildHeartbeat(url: string, settings: Settings, tab: browser.Tabs.Tab): Promise<Heartbeat> {
|
||||
if (!tab.id) {
|
||||
throw Error('Missing tab id.');
|
||||
}
|
||||
|
||||
const heartbeat = (
|
||||
(await browser.tabs.sendMessage(tab.id, { task: 'getHeartbeatFromPage', url })) as {
|
||||
heartbeat?: OptionalHeartbeat;
|
||||
}
|
||||
).heartbeat;
|
||||
|
||||
const entity = settings.loggingType === 'domain' ? getDomainFromUrl(url) : url;
|
||||
return {
|
||||
project: null,
|
||||
url: null,
|
||||
branch: heartbeat?.branch ?? '<<LAST_BRANCH>>',
|
||||
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),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Given the heartbeat and logging type it creates a payload and
|
||||
* sends an ajax post request to the API.
|
||||
*
|
||||
* @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,
|
||||
);
|
||||
}
|
||||
getCurrentTime(): string {
|
||||
const m = moment();
|
||||
return `${m.format('x').slice(0, -3)}.${m.format('x').slice(-3)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a promise with logging type variable.
|
||||
*
|
||||
* @returns {*}
|
||||
* @private
|
||||
*/
|
||||
async getLoggingType(): Promise<string> {
|
||||
const items = await browser.storage.sync.get({
|
||||
loggingType: config.loggingType,
|
||||
async sendHeartbeats(): Promise<void> {
|
||||
const settings = await browser.storage.sync.get({
|
||||
apiKey: config.apiKey,
|
||||
apiUrl: config.apiUrl,
|
||||
heartbeatApiEndPoint: config.heartbeatApiEndPoint,
|
||||
hostname: '',
|
||||
});
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates payload for the heartbeat and returns it as JSON.
|
||||
*
|
||||
* @param heartbeat
|
||||
* @param type
|
||||
* @param debug
|
||||
* @returns {*}
|
||||
* @private
|
||||
*/
|
||||
async preparePayload(heartbeat: SendHeartbeat, type: string): Promise<Record<string, unknown>> {
|
||||
const os = await this.getOperatingSystem();
|
||||
async putHeartbeatsBackInQueue(heartbeats: Heartbeat[]): Promise<void> {
|
||||
await Promise.all(
|
||||
heartbeats.map(async (heartbeat) => this.db?.add('heartbeatQueue', heartbeat)),
|
||||
);
|
||||
}
|
||||
|
||||
async getUserAgent(): Promise<string> {
|
||||
const os = await getOperatingSystem();
|
||||
let browserName = 'chrome';
|
||||
let userAgent;
|
||||
if (IS_FIREFOX) {
|
||||
@@ -346,96 +263,7 @@ class WakaTimeCore {
|
||||
} else {
|
||||
userAgent = navigator.userAgent.match(/Chrome\/\S+/g)?.[0];
|
||||
}
|
||||
const payload: Record<string, unknown> = {
|
||||
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');
|
||||
}
|
||||
}
|
||||
}
|
||||
return `${userAgent} ${os} ${browserName}-wakatime/${config.version}`;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
<meta charset="utf-8" />
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
|
||||
<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" />
|
||||
</head>
|
||||
|
||||
@@ -1,37 +1,30 @@
|
||||
// Generated by https://quicktype.io
|
||||
|
||||
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;
|
||||
export interface Heartbeat {
|
||||
branch?: string | null;
|
||||
category?: Category | null;
|
||||
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;
|
||||
language?: string | null;
|
||||
plugin?: string | null;
|
||||
project?: string | null;
|
||||
time: string;
|
||||
type: EntityType;
|
||||
}
|
||||
|
||||
export interface SendHeartbeat {
|
||||
branch?: string | null;
|
||||
hostname: string;
|
||||
project?: string | null;
|
||||
url: string;
|
||||
export enum Category {
|
||||
browsing = 'browsing',
|
||||
code_reviewing = 'code reviewing',
|
||||
coding = 'coding',
|
||||
communicating = 'communicating',
|
||||
debugging = 'debugging',
|
||||
designing = 'designing',
|
||||
meeting = 'meeting',
|
||||
}
|
||||
|
||||
export enum EntityType {
|
||||
app = 'app',
|
||||
domain = 'domain',
|
||||
file = 'file',
|
||||
url = 'url',
|
||||
}
|
||||
|
||||
export interface ProjectDetails {
|
||||
@@ -42,7 +35,6 @@ export interface ProjectDetails {
|
||||
project: string;
|
||||
}
|
||||
|
||||
export interface PostHeartbeatMessage {
|
||||
projectDetails?: ProjectDetails;
|
||||
recordHeartbeat: boolean;
|
||||
}
|
||||
export type HeartbeatsBulkResponse = { error?: string; responses?: HeartbeatResponse[] };
|
||||
|
||||
export type HeartbeatResponse = [{ data?: { id: string }; error?: string }, number];
|
||||
|
||||
52
src/types/sites.ts
Normal file
52
src/types/sites.ts
Normal 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;
|
||||
};
|
||||
@@ -1,12 +1,10 @@
|
||||
// Generated by https://quicktype.io
|
||||
|
||||
export interface SummariesPayload {
|
||||
data: Datum[];
|
||||
export interface Summaries {
|
||||
data: Summary[];
|
||||
end: string;
|
||||
start: string;
|
||||
}
|
||||
|
||||
export interface Datum {
|
||||
interface Summary {
|
||||
categories: Category[];
|
||||
dependencies: Category[];
|
||||
editors: Category[];
|
||||
@@ -18,7 +16,7 @@ export interface Datum {
|
||||
range: Range;
|
||||
}
|
||||
|
||||
export interface Category {
|
||||
interface Category {
|
||||
digital: string;
|
||||
hours: number;
|
||||
machine_name_id?: string;
|
||||
@@ -38,7 +36,7 @@ export interface GrandTotal {
|
||||
total_seconds: number;
|
||||
}
|
||||
|
||||
export interface Range {
|
||||
interface Range {
|
||||
date: string;
|
||||
end: string;
|
||||
start: string;
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
import browser from 'webextension-polyfill';
|
||||
import config from '../config/config';
|
||||
|
||||
export default function apiKeyInvalid(key?: string): string {
|
||||
const err = 'Invalid api key... check https://wakatime.com/settings for your key';
|
||||
if (!key) return err;
|
||||
@@ -11,11 +8,3 @@ export default function apiKeyInvalid(key?: string): string {
|
||||
if (!re.test(key)) return err;
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
76
src/utils/changeExtensionStatus.ts
Normal file
76
src/utils/changeExtensionStatus.ts
Normal 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
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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
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;
|
||||
};
|
||||
11
src/utils/operatingSystem.ts
Normal file
11
src/utils/operatingSystem.ts
Normal 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
75
src/utils/settings.ts
Normal 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
372
src/utils/sites.ts
Normal 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));
|
||||
});
|
||||
};
|
||||
11605
src/utils/stackexchange-sites.ts
Normal file
11605
src/utils/stackexchange-sites.ts
Normal file
File diff suppressed because it is too large
Load Diff
@@ -1,10 +1,30 @@
|
||||
import { AnyAction, Dispatch } from '@reduxjs/toolkit';
|
||||
import axios, { AxiosResponse } from 'axios';
|
||||
|
||||
import moment from 'moment';
|
||||
import config from '../config/config';
|
||||
import WakaTimeCore from '../core/WakaTimeCore';
|
||||
import { setApiKey, setLoggingEnabled, setTotalTimeLoggedToday } from '../reducers/configReducer';
|
||||
import { setUser } from '../reducers/currentUser';
|
||||
import { getHtmlContentByTabId } from '.';
|
||||
import changeExtensionState from './changeExtensionState';
|
||||
import { GrandTotal, Summaries } from '../types/summaries';
|
||||
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> => {
|
||||
if (!apiKey) {
|
||||
@@ -13,19 +33,60 @@ export const logUserIn = async (apiKey: string): Promise<void> => {
|
||||
}
|
||||
|
||||
try {
|
||||
await WakaTimeCore.checkAuth(apiKey);
|
||||
await checkAuth(apiKey);
|
||||
const items = await browser.storage.sync.get({ loggingEnabled: config.loggingEnabled });
|
||||
|
||||
if (items.loggingEnabled === true) {
|
||||
await changeExtensionState('allGood');
|
||||
} else {
|
||||
await changeExtensionState('notLogging');
|
||||
await changeExtensionState('trackingDisabled');
|
||||
}
|
||||
} catch (err: unknown) {
|
||||
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 (
|
||||
apiKey: string,
|
||||
dispatch: Dispatch<AnyAction>,
|
||||
@@ -36,7 +97,7 @@ export const fetchUserData = async (
|
||||
});
|
||||
apiKey = storage.apiKey as string;
|
||||
if (!apiKey) {
|
||||
apiKey = await WakaTimeCore.fetchApiKey();
|
||||
apiKey = await fetchApiKey();
|
||||
if (apiKey) {
|
||||
await browser.storage.sync.set({ apiKey });
|
||||
}
|
||||
@@ -51,8 +112,8 @@ export const fetchUserData = async (
|
||||
|
||||
try {
|
||||
const [data, totalTimeLoggedTodayResponse, items] = await Promise.all([
|
||||
WakaTimeCore.checkAuth(apiKey),
|
||||
WakaTimeCore.getTotalTimeLoggedToday(apiKey),
|
||||
checkAuth(apiKey),
|
||||
getTotalTimeLoggedToday(apiKey),
|
||||
browser.storage.sync.get({ loggingEnabled: config.loggingEnabled }),
|
||||
]);
|
||||
dispatch(setUser(data));
|
||||
@@ -60,23 +121,11 @@ export const fetchUserData = async (
|
||||
if (items.loggingEnabled === true) {
|
||||
await changeExtensionState('allGood');
|
||||
} else {
|
||||
await changeExtensionState('notLogging');
|
||||
await changeExtensionState('trackingDisabled');
|
||||
}
|
||||
|
||||
dispatch(setLoggingEnabled(items.loggingEnabled as boolean));
|
||||
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) {
|
||||
await changeExtensionState('notSignedIn');
|
||||
}
|
||||
|
||||
@@ -1,91 +1,64 @@
|
||||
const twoMinutes = 120000;
|
||||
import { getSite } from './utils/sites';
|
||||
|
||||
interface DesignProject {
|
||||
category: string;
|
||||
editor: string;
|
||||
language: string;
|
||||
project: string;
|
||||
}
|
||||
const oneMinute = 60000;
|
||||
const fiveMinutes = 300000;
|
||||
|
||||
const parseCanva = (): DesignProject | 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') ?? [],
|
||||
).find((inp) => inp.value === projectName);
|
||||
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) {
|
||||
/**
|
||||
* Debounces the execution of a function.
|
||||
*
|
||||
* @param {() => void} func - The function to debounce.
|
||||
* @param {number} [timeout] - The timeout for the debounce in milliseconds.
|
||||
* @param {number} [maxWaitTime] - The max time to debounce before forcing execution in milliseconds.
|
||||
* @returns {() => void} The debounced function.
|
||||
*/
|
||||
function debounce(func: () => void, timeout = oneMinute, maxWaitTime = fiveMinutes) {
|
||||
let timer: NodeJS.Timeout | undefined;
|
||||
return () => {
|
||||
if (timer) {
|
||||
return;
|
||||
let lastExecutionTime: number | undefined;
|
||||
return (...args: unknown[]) => {
|
||||
clearTimeout(timer);
|
||||
if (lastExecutionTime && lastExecutionTime + maxWaitTime < Date.now()) {
|
||||
lastExecutionTime = Date.now();
|
||||
func(...(args as []));
|
||||
}
|
||||
func();
|
||||
timer = setTimeout(() => {
|
||||
clearTimeout(timer);
|
||||
timer = undefined;
|
||||
lastExecutionTime = Date.now();
|
||||
func(...(args as []));
|
||||
}, timeout);
|
||||
};
|
||||
}
|
||||
|
||||
document.body.addEventListener(
|
||||
'click',
|
||||
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 });
|
||||
}
|
||||
const sendHeartbeat = debounce(async () => {
|
||||
chrome.runtime.sendMessage({ task: 'handleActivity' });
|
||||
});
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
@@ -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');
|
||||
});
|
||||
});
|
||||
@@ -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');
|
||||
});
|
||||
});
|
||||
@@ -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'});
|
||||
// });
|
||||
});
|
||||
@@ -8,14 +8,14 @@ describe('contains', 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 url = 'http://localhost/fooapp';
|
||||
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 url = 'http://localhost/fooapp';
|
||||
|
||||
@@ -58,7 +58,7 @@ const getConfigByBrowser = (isProd: boolean, browser: BrowserTypes): webpack.Con
|
||||
new webpack.DefinePlugin({
|
||||
['process.env.API_URL']: JSON.stringify('https://api.wakatime.com/api/v1'),
|
||||
['process.env.CURRENT_USER_API_URL']: JSON.stringify('/users/current'),
|
||||
['process.env.HEARTBEAT_API_URL']: JSON.stringify('/users/current/heartbeats'),
|
||||
['process.env.HEARTBEAT_API_URL']: JSON.stringify('/users/current/heartbeats.bulk'),
|
||||
['process.env.LOGOUT_USER_URL']: JSON.stringify('https://wakatime.com/logout'),
|
||||
['process.env.NODE_ENV']: JSON.stringify(isProd ? 'production' : 'development'),
|
||||
['process.env.SUMMARIES_API_URL']: JSON.stringify('/users/current/summaries'),
|
||||
|
||||
Reference in New Issue
Block a user