over the hump

This commit is contained in:
Alan Hamlett
2024-08-27 16:35:35 +02:00
parent d66b1b55ba
commit 115789dc6e
8 changed files with 11814 additions and 393 deletions

View File

@@ -1,7 +1,5 @@
import browser from 'webextension-polyfill'; import browser from 'webextension-polyfill';
import WakaTimeCore from './core/WakaTimeCore'; import WakaTimeCore from './core/WakaTimeCore';
import { PostHeartbeatMessage } from './types/heartbeats';
import { getHtmlContentByTabId } from './utils';
// Add a listener to resolve alarms // Add a listener to resolve alarms
browser.alarms.onAlarm.addListener(async (alarm) => { browser.alarms.onAlarm.addListener(async (alarm) => {
@@ -24,13 +22,7 @@ browser.alarms.create('heartbeatAlarm', { periodInMinutes: 2 });
* Whenever a active tab is changed it records a heartbeat with that tab url. * Whenever a active tab is changed it records a heartbeat with that tab url.
*/ */
browser.tabs.onActivated.addListener(async (activeInfo) => { browser.tabs.onActivated.addListener(async (activeInfo) => {
console.log('recording a heartbeat - active tab changed'); await WakaTimeCore.handleActivity(activeInfo.tabId);
let html = '';
try {
html = await getHtmlContentByTabId(activeInfo.tabId);
// eslint-disable-next-line no-empty
} catch (error: unknown) {}
await WakaTimeCore.recordHeartbeat(html);
}); });
/** /**
@@ -44,15 +36,10 @@ browser.windows.onFocusChanged.addListener(async (windowId) => {
currentWindow: true, currentWindow: true,
}); });
let html = '';
const tabId = tabs[0]?.id; const tabId = tabs[0]?.id;
if (tabId) { if (tabId) {
try { await WakaTimeCore.handleActivity(tabId);
html = await getHtmlContentByTabId(tabId);
// eslint-disable-next-line no-empty
} catch (error: unknown) {}
} }
await WakaTimeCore.recordHeartbeat(html);
} }
}); });
@@ -69,12 +56,7 @@ browser.tabs.onUpdated.addListener(async (tabId, changeInfo) => {
}); });
// If tab updated is the same as active tab // If tab updated is the same as active tab
if (tabId == tabs[0]?.id) { if (tabId == tabs[0]?.id) {
let html = ''; await WakaTimeCore.handleActivity(tabs[0].id);
try {
html = await getHtmlContentByTabId(tabId);
// eslint-disable-next-line no-empty
} catch (error: unknown) {}
await WakaTimeCore.recordHeartbeat(html);
} }
} }
}); });
@@ -87,16 +69,10 @@ self.addEventListener('activate', async () => {
await WakaTimeCore.createDB(); await WakaTimeCore.createDB();
}); });
browser.runtime.onMessage.addListener(async (request: PostHeartbeatMessage, sender) => { browser.runtime.onMessage.addListener(async (request: { task: string }, sender) => {
if (request.recordHeartbeat === true) { if (request.task === 'handleActivity') {
if (sender.tab?.id) { if (!sender.tab?.id) return;
let html = ''; await WakaTimeCore.handleActivity(sender.tab.id);
try {
html = await getHtmlContentByTabId(sender.tab.id);
// eslint-disable-next-line no-empty
} catch (error: unknown) {}
await WakaTimeCore.recordHeartbeat(html, request.projectDetails);
}
} }
}); });

View File

@@ -3,16 +3,15 @@ import browser, { Tabs } from 'webextension-polyfill';
/* eslint-disable no-fallthrough */ /* eslint-disable no-fallthrough */
/* eslint-disable default-case */ /* eslint-disable default-case */
import moment from 'moment'; import moment from 'moment';
import { getOperatingSystem, isCodeReviewing } from '../utils'; import { SiteInfo } from 'src/types/sites';
import { getOperatingSystem } from '../utils';
import { changeExtensionStatus } from '../utils/changeExtensionStatus'; import { changeExtensionStatus } from '../utils/changeExtensionStatus';
import getDomainFromUrl, { getDomain } from '../utils/getDomainFromUrl'; import getDomainFromUrl, { getDomain } from '../utils/getDomainFromUrl';
import { getSettings, Settings } from '../utils/settings'; import { getSettings, Settings } from '../utils/settings';
import config, { ExtensionStatus } from '../config/config'; import config, { ExtensionStatus } from '../config/config';
import { Heartbeat } from '../types/heartbeats'; import { EntityType, Heartbeat } from '../types/heartbeats';
import { getApiKey } from '../utils/apiKey'; import { getApiKey } from '../utils/apiKey';
import contains from '../utils/contains';
import { getHeartbeatFromPage } from '../utils/heartbeat';
import { getLoggingType } from '../utils/logging'; import { getLoggingType } from '../utils/logging';
class WakaTimeCore { class WakaTimeCore {
@@ -58,6 +57,13 @@ class WakaTimeCore {
} }
canSendHeartbeat(url: string, settings: Settings): boolean { 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;
}
}
if (!settings.trackSocialMedia) { if (!settings.trackSocialMedia) {
const domain = getDomain(url); const domain = getDomain(url);
if ( if (
@@ -86,13 +92,18 @@ class WakaTimeCore {
); );
} }
async handleActivity(url: string, heartbeat: Heartbeat) { async handleActivity(tabId: number) {
const settings = await getSettings(); const settings = await getSettings();
if (!settings.loggingEnabled) { if (!settings.loggingEnabled) {
await changeExtensionStatus('notLogging'); await changeExtensionStatus('notLogging');
return; return;
} }
const activeTab = await this.getCurrentTab(tabId);
if (!activeTab) return;
const url = activeTab.url as string;
if (!this.canSendHeartbeat(url, settings)) { if (!this.canSendHeartbeat(url, settings)) {
await changeExtensionStatus('ignored'); await changeExtensionStatus('ignored');
return; return;
@@ -102,173 +113,44 @@ class WakaTimeCore {
await changeExtensionStatus('allGood'); await changeExtensionStatus('allGood');
} }
const heartbeat = await this.buildHeartbeat(url, settings, activeTab);
if (!this.shouldSendHeartbeat(heartbeat)) return; if (!this.shouldSendHeartbeat(heartbeat)) return;
// append heartbeat to queue // append heartbeat to queue
await this.db?.add('cacheHeartbeats', heartbeat); await this.db?.add('cacheHeartbeats', heartbeat);
} }
/** async getCurrentTab(tabId: number): Promise<browser.Tabs.Tab | undefined> {
* Depending on various factors detects the current active tab URL or domain, const tabs: browser.Tabs.Tab[] = await browser.tabs.query({
* and sends it to WakaTime for logging. active: true,
*/ currentWindow: true,
async recordHeartbeat(html: string, payload: Record<string, unknown> = {}): Promise<void> {
const apiKey = await getApiKey();
if (!apiKey) {
return changeExtensionStatus('notLogging');
}
const items = await browser.storage.sync.get({
allowList: '',
denyList: '',
hostname: config.hostname,
loggingEnabled: config.loggingEnabled,
loggingStyle: config.loggingStyle,
socialMediaSites: config.socialMediaSites,
trackSocialMedia: config.trackSocialMedia,
}); });
if (items.loggingEnabled === true) { const activeTab = tabs[0];
await changeExtensionStatus('allGood'); if (tabId !== activeTab.id) return;
let newState = ''; return activeTab;
// Detects we are running this code in the extension scope
if (browser.idle as browser.Idle.Static | undefined) {
newState = await browser.idle.queryState(config.detectionIntervalInSeconds);
if (newState !== 'active') {
return changeExtensionStatus('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 changeExtensionStatus('ignored');
}
}
// Checks dev websites
const project = getHeartbeatFromPage(url, html);
// Check if code reviewing
const codeReviewing = isCodeReviewing(url);
if (codeReviewing) {
payload.category = 'code reviewing';
}
if (items.loggingStyle == 'deny') {
if (!contains(url, items.denyList as string)) {
await this.sendHeartbeat(
{
branch: null,
hostname: items.hostname as string,
project,
url,
},
apiKey,
payload,
);
} else {
await changeExtensionStatus('ignored');
console.log(`${url} is on denyList.`);
}
} else if (items.loggingStyle == 'allow') {
const heartbeat = this.getHeartbeat(url, items.allowList as string);
if (heartbeat.url) {
await this.sendHeartbeat(
{
...heartbeat,
branch: null,
hostname: items.hostname as string,
project: heartbeat.project ?? project,
},
apiKey,
payload,
);
} else {
await changeExtensionStatus('ignored');
console.log(`${url} is not on allowList.`);
}
} else {
throw Error(`Unknown logging styel: ${items.loggingStyle}`);
}
}
} }
/** async buildHeartbeat(url: string, settings: Settings, tab: browser.Tabs.Tab): Promise<Heartbeat> {
* Creates an array from list using \n as delimiter if (!tab.id) {
* and checks if any element in list is contained in the url. throw Error('Missing tab id.');
* Also checks if element is assigned to a project using @@ as delimiter
*
* @param url
* @param list
* @returns {object}
*/
getHeartbeat(url: string, list: string) {
const projectIndicatorCharacters = '@@';
const lines = list.split('\n');
for (let i = 0; i < lines.length; i++) {
// strip (http:// or https://) and trailing (`/` or `@@`)
const cleanLine = lines[i]
.trim()
.replace(/(\/|@@)$/, '')
.replace(/^(?:https?:\/\/)?/i, '');
if (cleanLine === '') continue;
const projectIndicatorIndex = cleanLine.lastIndexOf(projectIndicatorCharacters);
const projectIndicatorExists = projectIndicatorIndex > -1;
let projectName = null;
let urlFromLine = cleanLine;
if (projectIndicatorExists) {
const start = projectIndicatorIndex + projectIndicatorCharacters.length;
projectName = cleanLine.substring(start);
urlFromLine = cleanLine
.replace(cleanLine.substring(projectIndicatorIndex), '')
.replace(/\/$/, '');
}
const cleanUrl = url
.trim()
.replace(/(\/|@@)$/, '')
.replace(/^(?:https?:\/\/)?/i, '');
const startsWithUrl = cleanUrl.toLowerCase().includes(urlFromLine.toLowerCase());
if (startsWithUrl) {
return {
project: projectName,
url,
};
}
const lineRe = new RegExp(cleanLine.replace('.', '.').replace('*', '.*'));
// If url matches the current line return true
if (lineRe.test(url)) {
return {
project: null,
url,
};
}
} }
const heartbeat = (
(await browser.tabs.sendMessage(tab.id, { task: 'getHeartbeatFromPage', url })) as {
heartbeat?: SiteInfo;
}
).heartbeat;
const entity = settings.loggingType === 'domain' ? getDomainFromUrl(url) : url;
return { return {
project: null, branch: heartbeat?.branch,
url: null, category: heartbeat?.category,
entity: heartbeat?.entity ?? entity,
entityType: heartbeat?.entityType ?? (settings.loggingType as EntityType),
language: heartbeat?.language,
project: heartbeat?.project,
}; };
} }

View File

@@ -30,8 +30,3 @@ export interface ProjectDetails {
language: string; language: string;
project: string; project: string;
} }
export interface PostHeartbeatMessage {
projectDetails?: ProjectDetails;
recordHeartbeat: boolean;
}

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

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

View File

@@ -1,8 +1,7 @@
import { parse } from 'node-html-parser'; import { HeartbeatParser, KnownSite, SiteParser, StackExchangeSite } from '../types/sites';
import { STACKEXCHANGE_SITES } from './stackexchange-sites';
type ProjectNameExtractor = (url: string, html: string) => string | null; const GitHub: HeartbeatParser = (url: string) => {
const GitHub: ProjectNameExtractor = (url: string, html: string): string | null => {
const { hostname } = new URL(url); const { hostname } = new URL(url);
const match = url.match(/(?<=github\.(?:com|dev)\/[^/]+\/)([^/?#]+)/); const match = url.match(/(?<=github\.(?:com|dev)\/[^/]+\/)([^/?#]+)/);
@@ -22,7 +21,7 @@ const GitHub: ProjectNameExtractor = (url: string, html: string): string | null
return null; return null;
}; };
const GitLab: ProjectNameExtractor = (url: string, html: string): string | null => { const GitLab: HeartbeatParser = (url: string, html: string): string | null => {
const match = url.match(/(?<=gitlab\.com\/[^/]+\/)([^/?#]+)/); const match = url.match(/(?<=gitlab\.com\/[^/]+\/)([^/?#]+)/);
if (match) { if (match) {
@@ -37,7 +36,7 @@ const GitLab: ProjectNameExtractor = (url: string, html: string): string | null
return null; return null;
}; };
const BitBucket: ProjectNameExtractor = (url: string, html: string): string | null => { const BitBucket: HeartbeatParser = (url: string, html: string): string | null => {
const match = url.match(/(?<=bitbucket\.org\/[^/]+\/)([^/?#]+)/); const match = url.match(/(?<=bitbucket\.org\/[^/]+\/)([^/?#]+)/);
if (match) { if (match) {
@@ -53,7 +52,7 @@ const BitBucket: ProjectNameExtractor = (url: string, html: string): string | nu
return null; return null;
}; };
const TravisCI: ProjectNameExtractor = (url: string, html: string): string | null => { const TravisCI: HeartbeatParser = (url: string, html: string): string | null => {
const match = url.match(/(?<=app\.travis-ci\.com\/[^/]+\/[^/]+\/)([^/?#]+)/); const match = url.match(/(?<=app\.travis-ci\.com\/[^/]+\/[^/]+\/)([^/?#]+)/);
if (match) { if (match) {
@@ -67,7 +66,7 @@ const TravisCI: ProjectNameExtractor = (url: string, html: string): string | nul
return null; return null;
}; };
const CircleCI: ProjectNameExtractor = (url: string, html: string): string | null => { const CircleCI: HeartbeatParser = (url: string, html: string): string | null => {
const projectPageMatch = url.match( const projectPageMatch = url.match(
/(?<=app\.circleci\.com\/projects\/[^/]+\/[^/]+\/[^/]+\/)([^/?#]+)/, /(?<=app\.circleci\.com\/projects\/[^/]+\/[^/]+\/[^/]+\/)([^/?#]+)/,
); );
@@ -104,7 +103,7 @@ const CircleCI: ProjectNameExtractor = (url: string, html: string): string | nul
return null; return null;
}; };
const Vercel: ProjectNameExtractor = (url: string, html: string): string | null => { const Vercel: HeartbeatParser = (url: string, html: string): string | null => {
const match = url.match(/(?<=vercel\.com\/[^/]+\/)([^/?#]+)/); const match = url.match(/(?<=vercel\.com\/[^/]+\/)([^/?#]+)/);
if (match) { if (match) {
@@ -120,22 +119,19 @@ const Vercel: ProjectNameExtractor = (url: string, html: string): string | null
return null; return null;
}; };
const ProjectNameExtractors: ProjectNameExtractor[] = [ const StackOverflow: HeartbeatParser = (url: string, html: string): string | null => {
GitHub, const match = url.match(/(?<=vercel\.com\/[^/]+\/)([^/?#]+)/);
GitLab,
BitBucket,
TravisCI,
CircleCI,
Vercel,
];
export const getHeartbeatFromPage = (): string | null => { if (match) {
for (const projectNameExtractor of ProjectNameExtractors) { const root = parse(html);
const projectName = projectNameExtractor(url, html); // this regex extracts the project name from the title
if (projectName) { // eg. title: test-website - Overview Vercel
return projectName; const match2 = root.querySelector('title')?.textContent.match(/^[^\s]+(?=\s-\s)/);
if (match2 && match2[0] === match[0]) {
return match[0];
} }
} }
return null; return null;
}; };
@@ -156,3 +152,81 @@ export const getHtmlContentByTabId = async (tabId: number): Promise<string> => {
}; };
return response.html; return response.html;
}; };
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\//],
},
circleci: {
parser: CircleCI,
urls: [/^https?:\/\/(.+\.)?circleci.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\//],
},
stackoverflow: {
parser: StackOverflow,
urls: stackExchangeDomains,
},
travisci: {
parser: TravisCI,
urls: [/^https?:\/\/(.+\.)?travis-ci.com\//],
},
vercel: {
parser: Vercel,
urls: [/^https?:\/\/(.+\.)?vercel.com\//],
},
};
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));
});
};

View File

@@ -1,158 +0,0 @@
import { parse } from 'node-html-parser';
type ProjectNameExtractor = (url: string, html: string) => string | null;
const GitHub: ProjectNameExtractor = (url: string, html: string): string | null => {
const { hostname } = new URL(url);
const match = url.match(/(?<=github\.(?:com|dev)\/[^/]+\/)([^/?#]+)/);
if (match) {
if (hostname.endsWith('.com')) {
const root = parse(html);
const repoName = root
.querySelector('meta[name=octolytics-dimension-repository_nwo]')
?.getAttribute('content');
if (!repoName || repoName.split('/')[1] !== match[0]) {
return null;
}
}
return match[0];
}
return null;
};
const GitLab: ProjectNameExtractor = (url: string, html: string): string | null => {
const match = url.match(/(?<=gitlab\.com\/[^/]+\/)([^/?#]+)/);
if (match) {
const root = parse(html);
const repoName = root.querySelector('body')?.getAttribute('data-project-full-path');
if (!repoName || repoName.split('/')[1] !== match[0]) {
return null;
}
return match[0];
}
return null;
};
const BitBucket: ProjectNameExtractor = (url: string, html: string): string | null => {
const match = url.match(/(?<=bitbucket\.org\/[^/]+\/)([^/?#]+)/);
if (match) {
const root = parse(html);
// this regex extracts the project name from the title
// eg. title: jhondoe / my-test-repo — Bitbucket
const match2 = root.querySelector('title')?.textContent.match(/(?<=\/\s)([^/\s]+)(?=\s—)/);
if (match2 && match2[0] === match[0]) {
return match[0];
}
}
return null;
};
const TravisCI: ProjectNameExtractor = (url: string, html: string): string | null => {
const match = url.match(/(?<=app\.travis-ci\.com\/[^/]+\/[^/]+\/)([^/?#]+)/);
if (match) {
const root = parse(html);
const projectName = root.querySelector('#ember737')?.textContent;
if (projectName === match[0]) {
return match[0];
}
}
return null;
};
const CircleCI: ProjectNameExtractor = (url: string, html: string): string | null => {
const projectPageMatch = url.match(
/(?<=app\.circleci\.com\/projects\/[^/]+\/[^/]+\/[^/]+\/)([^/?#]+)/,
);
if (projectPageMatch) {
const root = parse(html);
const seconndBreadcrumbLabel = root.querySelector(
'#__next > div:nth-child(2) > div > div > main > div > header > div:nth-child(1) > ol > li:nth-child(2) > div > div > span',
)?.textContent;
const seconndBreadcrumbValue = root.querySelector(
'#__next > div:nth-child(2) > div > div > main > div > header > div:nth-child(1) > ol > li:nth-child(2) > div > span',
)?.textContent;
if (seconndBreadcrumbLabel === 'Project' && seconndBreadcrumbValue === projectPageMatch[0]) {
return projectPageMatch[0];
}
}
const settingsPageMatch = url.match(
/(?<=app\.circleci\.com\/settings\/project\/[^/]+\/[^/]+\/)([^/?#]+)/,
);
if (settingsPageMatch) {
const root = parse(html);
const pageTitle = root.querySelector(
'#__next > div > div:nth-child(1) > header > div > div:nth-child(2) > h1',
)?.textContent;
const pageSubtitle = root.querySelector(
'#__next > div > div:nth-child(1) > header > div > div:nth-child(2) > div',
)?.textContent;
if (pageTitle === 'Project Settings' && pageSubtitle === settingsPageMatch[0]) {
return settingsPageMatch[0];
}
}
return null;
};
const Vercel: ProjectNameExtractor = (url: string, html: string): string | null => {
const match = url.match(/(?<=vercel\.com\/[^/]+\/)([^/?#]+)/);
if (match) {
const root = parse(html);
// this regex extracts the project name from the title
// eg. title: test-website - Overview Vercel
const match2 = root.querySelector('title')?.textContent.match(/^[^\s]+(?=\s-\s)/);
if (match2 && match2[0] === match[0]) {
return match[0];
}
}
return null;
};
const ProjectNameExtractors: ProjectNameExtractor[] = [
GitHub,
GitLab,
BitBucket,
TravisCI,
CircleCI,
Vercel,
];
export const getHeartbeatFromPage = (): string | null => {
for (const projectNameExtractor of ProjectNameExtractors) {
const projectName = projectNameExtractor(url, html);
if (projectName) {
return projectName;
}
}
return null;
};
const CODE_REVIEW_URL_REG_LIST = [/github.com\/[^/]+\/[^/]+\/pull\/\d+\/files/];
export const isCodeReviewing = (url: string): boolean => {
for (const reg of CODE_REVIEW_URL_REG_LIST) {
if (url.match(reg)) {
return true;
}
}
return false;
};
export const getHtmlContentByTabId = async (tabId: number): Promise<string> => {
const response = (await browser.tabs.sendMessage(tabId, { message: 'get_html' })) as {
html: string;
};
return response.html;
};

File diff suppressed because it is too large Load Diff

View File

@@ -1,4 +1,4 @@
import { getHeartbeatFromPage } from './utils/heartbeat'; import { getSite } from './utils/heartbeat';
const oneMinute = 60000; const oneMinute = 60000;
const fiveMinutes = 300000; const fiveMinutes = 300000;
@@ -56,16 +56,6 @@ const parseMeet = (): DesignProject | undefined => {
}; };
}; };
const getParser: {
[key: string]:
| (() => { editor: string; language: string; project: string } | undefined)
| undefined;
} = {
'meet.google.com': parseMeet,
'www.canva.com': parseCanva,
'www.figma.com': parseFigma,
};
/** /**
* Debounces the execution of a function. * Debounces the execution of a function.
* *
@@ -91,15 +81,22 @@ function debounce(func: () => void, timeout = oneMinute, maxWaitTime = fiveMinut
} }
const sendHeartbeat = debounce(async () => { const sendHeartbeat = debounce(async () => {
const heartbeat = getHeartbeatFromPage(); chrome.runtime.sendMessage({ task: 'handleActivity' });
chrome.runtime.sendMessage({ heartbeat: heartbeat, task: 'sendHeartbeat' });
}); });
chrome.runtime.onMessage.addListener((request: { message: string }, sender, sendResponse) => { chrome.runtime.onMessage.addListener(
if (request.message === 'get_html') { (request: { task: string; url: string }, sender, sendResponse) => {
sendResponse({ html: document.documentElement.outerHTML }); 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('click', sendHeartbeat, true);