chore: add support for Content scripts (#182)
* chore: add support for Content scripts * chore: run script bae on browser * chore: content script supporting canva website * chore: add 2 minutes debounce for onclik events * chore: add debounce for keypress events
This commit is contained in:
committed by
GitHub
parent
c2ead5149d
commit
7d795f854f
@@ -8,6 +8,8 @@ import config from '../config/config';
|
||||
import { SendHeartbeat } from '../types/heartbeats';
|
||||
import { GrandTotal, SummariesPayload } from '../types/summaries';
|
||||
import { ApiKeyPayload, AxiosUserResponse, User } from '../types/user';
|
||||
import { generateProjectFromDevSites, IS_FIREFOX } from '../utils';
|
||||
import { getApiKey } from '../utils/apiKey';
|
||||
import changeExtensionState from '../utils/changeExtensionState';
|
||||
import contains from '../utils/contains';
|
||||
import getDomainFromUrl from '../utils/getDomainFromUrl';
|
||||
@@ -106,20 +108,12 @@ class WakaTimeCore {
|
||||
return userPayload.data.data;
|
||||
}
|
||||
|
||||
async getApiKey(): Promise<string> {
|
||||
const storage = await browser.storage.sync.get({
|
||||
apiKey: config.apiKey,
|
||||
});
|
||||
const apiKey = storage.apiKey as string;
|
||||
return apiKey;
|
||||
}
|
||||
|
||||
/**
|
||||
* Depending on various factors detects the current active tab URL or domain,
|
||||
* and sends it to WakaTime for logging.
|
||||
*/
|
||||
async recordHeartbeat(): Promise<void> {
|
||||
const apiKey = await this.getApiKey();
|
||||
const apiKey = await getApiKey();
|
||||
if (!apiKey) {
|
||||
return changeExtensionState('notLogging');
|
||||
}
|
||||
@@ -151,7 +145,7 @@ class WakaTimeCore {
|
||||
}
|
||||
|
||||
// Checks dev websites
|
||||
const project = this.generateProjectFromDevSites(currentActiveTab.url as string);
|
||||
const project = generateProjectFromDevSites(currentActiveTab.url as string);
|
||||
|
||||
if (items.loggingStyle == 'blacklist') {
|
||||
if (!contains(currentActiveTab.url as string, items.blacklist as string)) {
|
||||
@@ -303,17 +297,6 @@ class WakaTimeCore {
|
||||
return items.loggingType;
|
||||
}
|
||||
|
||||
generateProjectFromDevSites(url: string): string | null {
|
||||
const githubUrls = ['https://github.com/', 'https://github.dev/'];
|
||||
for (const githubUrl of githubUrls) {
|
||||
if (url.startsWith(githubUrl)) {
|
||||
const newUrl = url.replace(githubUrl, '');
|
||||
return newUrl.split('/')[1] || null;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates payload for the heartbeat and returns it as JSON.
|
||||
*
|
||||
@@ -326,7 +309,7 @@ class WakaTimeCore {
|
||||
preparePayload(heartbeat: SendHeartbeat, type: string): Record<string, unknown> {
|
||||
let browserName = 'chrome';
|
||||
let userAgent;
|
||||
if (navigator.userAgent.includes('Firefox')) {
|
||||
if (IS_FIREFOX) {
|
||||
browserName = 'firefox';
|
||||
userAgent = navigator.userAgent.match(/Firefox\/\S+/g)![0];
|
||||
} else {
|
||||
@@ -393,7 +376,7 @@ class WakaTimeCore {
|
||||
* @param requests
|
||||
*/
|
||||
async sendCachedHeartbeatsRequest(): Promise<void> {
|
||||
const apiKey = await this.getApiKey();
|
||||
const apiKey = await getApiKey();
|
||||
if (!apiKey) {
|
||||
return changeExtensionState('notLogging');
|
||||
}
|
||||
|
||||
@@ -11,6 +11,13 @@
|
||||
"service_worker": "background.js",
|
||||
"type": "module"
|
||||
},
|
||||
"content_scripts": [
|
||||
{
|
||||
"matches": ["<all_urls>"],
|
||||
"js": ["wakatimeScript.js"],
|
||||
"run_at": "document_end"
|
||||
}
|
||||
],
|
||||
"description": "Automatic time tracking for Chrome.",
|
||||
"devtools_page": "devtools.html",
|
||||
"homepage_url": "https://wakatime.com",
|
||||
@@ -26,5 +33,5 @@
|
||||
"page": "options.html"
|
||||
},
|
||||
"permissions": ["alarms", "tabs", "storage", "idle"],
|
||||
"version": "3.0.8"
|
||||
"version": "3.0.9"
|
||||
}
|
||||
|
||||
@@ -17,6 +17,13 @@
|
||||
"strict_min_version": "48.0"
|
||||
}
|
||||
},
|
||||
"content_scripts": [
|
||||
{
|
||||
"matches": ["<all_urls>"],
|
||||
"js": ["wakatimeScript.js"],
|
||||
"run_at": "document_end"
|
||||
}
|
||||
],
|
||||
"description": "Automatic time tracking for Chrome.",
|
||||
"devtools_page": "devtools.html",
|
||||
"homepage_url": "https://wakatime.com",
|
||||
@@ -39,5 +46,5 @@
|
||||
"storage",
|
||||
"idle"
|
||||
],
|
||||
"version": "3.0.8"
|
||||
"version": "3.0.9"
|
||||
}
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
import { configureStore, Store, combineReducers } from '@reduxjs/toolkit';
|
||||
import { logger } from 'redux-logger';
|
||||
import { reduxBatch } from '@manaflair/redux-batch';
|
||||
import devToolsEnhancer from 'remote-redux-devtools';
|
||||
import currentUserReducer, { initialState as InitalCurrentUser } from '../reducers/currentUser';
|
||||
import { combineReducers, configureStore, Store } from '@reduxjs/toolkit';
|
||||
import { logger } from 'redux-logger';
|
||||
import configReducer, { initialConfigState } from '../reducers/configReducer';
|
||||
import isProd from '../utils/isProd';
|
||||
import currentUserReducer, { initialState as InitalCurrentUser } from '../reducers/currentUser';
|
||||
|
||||
// Create the root reducer separately so we can extract the RootState type
|
||||
const rootReducer = combineReducers({
|
||||
@@ -19,14 +17,9 @@ const preloadedState: RootState = {
|
||||
currentUser: InitalCurrentUser,
|
||||
};
|
||||
|
||||
export default (appName: string): Store<RootState> => {
|
||||
export default (): Store<RootState> => {
|
||||
const enhancers = [];
|
||||
enhancers.push(reduxBatch);
|
||||
if (!isProd()) {
|
||||
enhancers.push(
|
||||
devToolsEnhancer({ hostname: 'localhost', name: appName, port: 8000, realtime: true }),
|
||||
);
|
||||
}
|
||||
const store = configureStore({
|
||||
devTools: true,
|
||||
enhancers,
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
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;
|
||||
@@ -8,3 +11,11 @@ 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,5 +1,6 @@
|
||||
import browser from 'webextension-polyfill';
|
||||
import config from '../config/config';
|
||||
import { IS_FIREFOX } from '.';
|
||||
|
||||
type ColorIconTypes = 'gray' | 'red' | 'white' | '';
|
||||
|
||||
@@ -21,7 +22,7 @@ export default async function changeExtensionIcon(color?: ColorIconTypes): Promi
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
|
||||
if (browser.browserAction) {
|
||||
if (IS_FIREFOX) {
|
||||
await browser.browserAction.setIcon({ path: path }); // Support for FF with manifest V2
|
||||
} else {
|
||||
await browser.action.setIcon({ path: path }); // Support for Chrome with manifest V3
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import browser from 'webextension-polyfill';
|
||||
import config from '../config/config';
|
||||
import { IS_FIREFOX } from '.';
|
||||
|
||||
/**
|
||||
* It changes the extension title
|
||||
@@ -13,7 +14,7 @@ export default async function changeExtensionTooltip(text: string): Promise<void
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
|
||||
if (browser.browserAction) {
|
||||
if (IS_FIREFOX) {
|
||||
await browser.browserAction.setTitle({ title: text }); // Support for FF with manifest V2
|
||||
} else {
|
||||
await browser.action.setTitle({ title: text }); // Support for Chrome with manifest V3
|
||||
|
||||
14
src/utils/index.ts
Normal file
14
src/utils/index.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
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 generateProjectFromDevSites = (url: string): string | null => {
|
||||
const githubUrls = ['https://github.com/', 'https://github.dev/'];
|
||||
for (const githubUrl of githubUrls) {
|
||||
if (url.startsWith(githubUrl)) {
|
||||
const newUrl = url.replace(githubUrl, '');
|
||||
return newUrl.split('/')[1] || null;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
};
|
||||
289
src/wakatimeScript.ts
Normal file
289
src/wakatimeScript.ts
Normal file
@@ -0,0 +1,289 @@
|
||||
import moment from 'moment';
|
||||
import browser from 'webextension-polyfill';
|
||||
import config from './config/config';
|
||||
import { SendHeartbeat } from './types/heartbeats';
|
||||
import { generateProjectFromDevSites, IS_FIREFOX } from './utils';
|
||||
import { getApiKey } from './utils/apiKey';
|
||||
import contains from './utils/contains';
|
||||
import getDomainFromUrl from './utils/getDomainFromUrl';
|
||||
|
||||
const twoMinutes = 120000;
|
||||
|
||||
/**
|
||||
* 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}
|
||||
*/
|
||||
const 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 schemaHttpExists = url.match(/^http:\/\//i);
|
||||
const schemaHttpsExists = url.match(/^https:\/\//i);
|
||||
let schema = '';
|
||||
if (schemaHttpExists) {
|
||||
schema = 'http://';
|
||||
}
|
||||
if (schemaHttpsExists) {
|
||||
schema = 'https://';
|
||||
}
|
||||
const cleanUrl = url
|
||||
.trim()
|
||||
.replace(/(\/|@@)$/, '')
|
||||
.replace(/^(?:https?:\/\/)?/i, '');
|
||||
const startsWithUrl = cleanUrl.toLowerCase().includes(urlFromLine.toLowerCase());
|
||||
if (startsWithUrl) {
|
||||
return {
|
||||
project: projectName,
|
||||
url: schema + urlFromLine,
|
||||
};
|
||||
}
|
||||
|
||||
const lineRe = new RegExp(cleanLine.replace('.', '.').replace('*', '.*'));
|
||||
|
||||
// If url matches the current line return true
|
||||
if (lineRe.test(url)) {
|
||||
return {
|
||||
project: null,
|
||||
url: schema + urlFromLine,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
project: null,
|
||||
url: null,
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Sends AJAX request with payload to the heartbeat API as JSON.
|
||||
*
|
||||
* @param payload
|
||||
* @param method
|
||||
* @returns {*}
|
||||
*/
|
||||
const sendPostRequestToApi = async (
|
||||
payload: Record<string, unknown>,
|
||||
apiKey = '',
|
||||
hostname = '',
|
||||
): Promise<void> => {
|
||||
try {
|
||||
const request: RequestInit = {
|
||||
body: JSON.stringify(payload),
|
||||
credentials: 'omit',
|
||||
method: 'POST',
|
||||
};
|
||||
if (hostname) {
|
||||
request.headers = {
|
||||
'X-Machine-Name': hostname,
|
||||
};
|
||||
}
|
||||
const response = await fetch(`${config.heartbeatApiUrl}?api_key=${apiKey}`, request);
|
||||
await response.json();
|
||||
} catch (err: unknown) {
|
||||
console.log('Error', err);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Creates payload for the heartbeat and returns it as JSON.
|
||||
*
|
||||
* @param heartbeat
|
||||
* @param type
|
||||
* @param debug
|
||||
* @returns {*}
|
||||
* @private
|
||||
*/
|
||||
const preparePayload = (heartbeat: SendHeartbeat, type: string): Record<string, unknown> => {
|
||||
let browserName = 'chrome';
|
||||
let userAgent;
|
||||
if (IS_FIREFOX) {
|
||||
browserName = 'firefox';
|
||||
userAgent = navigator.userAgent.match(/Firefox\/\S+/g)![0];
|
||||
} 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} ${browserName}-wakatime/${config.version}`,
|
||||
};
|
||||
|
||||
if (heartbeat.project) {
|
||||
payload.project = heartbeat.project;
|
||||
}
|
||||
|
||||
return payload;
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns a promise with logging type variable.
|
||||
*
|
||||
* @returns {*}
|
||||
* @private
|
||||
*/
|
||||
const getLoggingType = async (): Promise<string> => {
|
||||
const items = await browser.storage.sync.get({
|
||||
loggingType: config.loggingType,
|
||||
});
|
||||
|
||||
return items.loggingType;
|
||||
};
|
||||
|
||||
/**
|
||||
* Given the heartbeat and logging type it creates a payload and
|
||||
* sends an ajax post request to the API.
|
||||
*
|
||||
* @param heartbeat
|
||||
* @param debug
|
||||
*/
|
||||
const sendHeartbeat = async (
|
||||
heartbeat: SendHeartbeat,
|
||||
apiKey: string,
|
||||
navigationPayload: Record<string, unknown>,
|
||||
): Promise<void> => {
|
||||
let payload;
|
||||
|
||||
const loggingType = await getLoggingType();
|
||||
// Get only the domain from the entity.
|
||||
// And send that in heartbeat
|
||||
if (loggingType == 'domain') {
|
||||
heartbeat.url = getDomainFromUrl(heartbeat.url);
|
||||
payload = preparePayload(heartbeat, 'domain');
|
||||
await sendPostRequestToApi({ ...payload, ...navigationPayload }, apiKey, heartbeat.hostname);
|
||||
}
|
||||
// Send entity in heartbeat
|
||||
else if (loggingType == 'url') {
|
||||
payload = preparePayload(heartbeat, 'url');
|
||||
await sendPostRequestToApi({ ...payload, ...navigationPayload }, apiKey, heartbeat.hostname);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Depending on various factors detects the current active tab URL or domain,
|
||||
* and sends it to WakaTime for logging.
|
||||
*/
|
||||
const recordHeartbeat = async (apiKey: string, payload: Record<string, unknown>): Promise<void> => {
|
||||
const items = await browser.storage.sync.get({
|
||||
blacklist: '',
|
||||
hostname: config.hostname,
|
||||
loggingEnabled: config.loggingEnabled,
|
||||
loggingStyle: config.loggingStyle,
|
||||
socialMediaSites: config.socialMediaSites,
|
||||
trackSocialMedia: config.trackSocialMedia,
|
||||
whitelist: '',
|
||||
});
|
||||
if (items.loggingEnabled === true) {
|
||||
if (!items.trackSocialMedia) {
|
||||
if (contains(document.URL, items.socialMediaSites as string)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Checks dev websites
|
||||
const project = generateProjectFromDevSites(document.URL);
|
||||
|
||||
if (items.loggingStyle == 'blacklist') {
|
||||
if (!contains(document.URL, items.blacklist as string)) {
|
||||
await sendHeartbeat(
|
||||
{
|
||||
hostname: items.hostname as string,
|
||||
project,
|
||||
url: document.URL,
|
||||
},
|
||||
apiKey,
|
||||
payload,
|
||||
);
|
||||
} else {
|
||||
console.log(`${document.URL} is on a blacklist.`);
|
||||
}
|
||||
}
|
||||
|
||||
if (items.loggingStyle == 'whitelist') {
|
||||
const heartbeat = getHeartbeat(document.URL, items.whitelist as string);
|
||||
if (heartbeat.url) {
|
||||
await sendHeartbeat(
|
||||
{
|
||||
...heartbeat,
|
||||
hostname: items.hostname as string,
|
||||
project: heartbeat.project ?? project,
|
||||
},
|
||||
apiKey,
|
||||
payload,
|
||||
);
|
||||
} else {
|
||||
console.log(`${document.URL} is not on a whitelist.`);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const init = async () => {
|
||||
const apiKey = await getApiKey();
|
||||
if (!apiKey) return;
|
||||
|
||||
const { hostname } = document.location;
|
||||
const canvaProject = document.getElementsByClassName('rF765A');
|
||||
|
||||
if (hostname === 'www.canva.com' && canvaProject.length > 0) {
|
||||
const ogTitle = (document.head.querySelector('meta[property="og:title"]') as HTMLMetaElement)
|
||||
.content;
|
||||
await recordHeartbeat(apiKey, {
|
||||
category: 'Designing',
|
||||
editor: 'Canva',
|
||||
language: 'Canva Design',
|
||||
project: ogTitle,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
function debounce(func: () => void, timeout = twoMinutes) {
|
||||
let timer: NodeJS.Timeout | undefined;
|
||||
return () => {
|
||||
if (timer) {
|
||||
return;
|
||||
}
|
||||
func();
|
||||
timer = setTimeout(() => {
|
||||
clearTimeout(timer);
|
||||
timer = undefined;
|
||||
}, timeout);
|
||||
};
|
||||
}
|
||||
|
||||
document.body.addEventListener(
|
||||
'click',
|
||||
debounce(() => init()),
|
||||
true,
|
||||
);
|
||||
|
||||
document.body.addEventListener(
|
||||
'keypress',
|
||||
debounce(() => init()),
|
||||
true,
|
||||
);
|
||||
Reference in New Issue
Block a user