diff --git a/src/components/Options.tsx b/src/components/Options.tsx index 156f264..414c32e 100644 --- a/src/components/Options.tsx +++ b/src/components/Options.tsx @@ -2,31 +2,24 @@ import React, { useEffect, useRef, useState } from 'react'; import config, { SuccessOrFailType } from '../config/config'; import { IS_CHROME } from '../utils'; import apiKeyInvalid from '../utils/apiKey'; +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({ alertText: config.alert.success.text, alertType: config.alert.success.type, + allowList: [], apiKey: '', apiUrl: config.apiUrl, - blacklist: '', + denyList: [], hostname: '', loading: false, loggingStyle: config.loggingStyle, @@ -34,45 +27,15 @@ export default function Options(): JSX.Element { socialMediaSites: config.socialMediaSites, theme: config.theme, trackSocialMedia: config.trackSocialMedia, - whitelist: '', }); const loggingStyleRef = useRef(null); const restoreSettings = async (): Promise => { - 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 +46,60 @@ 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, + hostname: state.hostname, + 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 +108,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 ( ); } - return ( ); }; @@ -206,10 +162,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)} > - - + + @@ -223,7 +179,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)} > @@ -238,7 +194,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)} > diff --git a/src/config/config.test.ts b/src/config/config.test.ts index 7d357eb..6fc1980 100644 --- a/src/config/config.test.ts +++ b/src/config/config.test.ts @@ -49,7 +49,7 @@ describe('wakatime config', () => { "heartbeatApiEndPoint": "/users/current/heartbeats", "hostname": "", "loggingEnabled": true, - "loggingStyle": "blacklist", + "loggingStyle": "deny", "loggingType": "domain", "logoutUserUrl": "https://wakatime.com/logout", "name": "WakaTime", @@ -73,17 +73,15 @@ describe('wakatime config', () => { "allGood", "notLogging", "notSignedIn", - "blacklisted", - "whitelisted", + "ignored", ], "summariesApiEndPoint": "/users/current/summaries", "theme": "light", "tooltips": { "allGood": "", - "blacklisted": "This URL is blacklisted", + "ignored": "This URL is ignored", "notLogging": "Not logging", "notSignedIn": "Not signed In", - "whitelisted": "This URL is not on your whitelist", }, "trackSocialMedia": true, "version": "test-version", diff --git a/src/config/config.ts b/src/config/config.ts index f10f19c..02af5b6 100644 --- a/src/config/config.ts +++ b/src/config/config.ts @@ -3,16 +3,18 @@ import browser from 'webextension-polyfill'; /** * Logging */ -export type ApiStates = 'allGood' | 'notLogging' | 'notSignedIn' | 'blacklisted' | 'whitelisted'; +export type ApiStates = 'allGood' | 'notLogging' | '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. */ @@ -41,10 +43,9 @@ interface Colors { */ interface Tooltips { allGood: string; - blacklisted: string; + ignored: string; notLogging: string; notSignedIn: string; - whitelisted: string; } export interface Config { @@ -97,7 +98,7 @@ export interface Config { /** * Options for theme */ - theme: 'light'; + theme: Theme; tooltips: Tooltips; trackSocialMedia: boolean; /** @@ -152,7 +153,7 @@ const config: Config = { 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', 'notLogging', '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', + ignored: 'This URL is ignored', notLogging: 'Not logging', notSignedIn: 'Not signed In', - whitelisted: 'This URL is not on your whitelist', }, trackSocialMedia: true, diff --git a/src/core/WakaTimeCore.ts b/src/core/WakaTimeCore.ts index 9c6f4f8..b66fde1 100644 --- a/src/core/WakaTimeCore.ts +++ b/src/core/WakaTimeCore.ts @@ -1,21 +1,23 @@ -/* 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 { IS_EDGE, IS_FIREFOX, getOperatingSystem, isCodeReviewing } from '../utils'; +import { getHeartbeatFromPage } from '../utils/heartbeat'; +/* eslint-disable no-fallthrough */ +/* eslint-disable default-case */ +import getDomainFromUrl, { getDomain } from '../utils/getDomainFromUrl'; + import config from '../config/config'; -import { 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 { Heartbeat } from '../types/heartbeats'; import { getApiKey } from '../utils/apiKey'; import changeExtensionState from '../utils/changeExtensionState'; import contains from '../utils/contains'; -import getDomainFromUrl, { getDomain } from '../utils/getDomainFromUrl'; +import { getLoggingType } from '../utils/logging'; class WakaTimeCore { tabsWithDevtoolsOpen: Tabs.Tab[]; + lastHeartbeat: Heartbeat | undefined; + lastHeartbeatSentAt = 0; db: IDBPDatabase | undefined; constructor() { this.tabsWithDevtoolsOpen = []; @@ -46,68 +48,57 @@ class WakaTimeCore { 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 { - const items = await browser.storage.sync.get({ - apiUrl: config.apiUrl, - summariesApiEndPoint: config.summariesApiEndPoint, - }); + async processHeartbeat(heartbeat: Heartbeat) { + const apiKey = await getApiKey(); + if (!apiKey) return changeExtensionState('notLogging'); - const today = moment().format('YYYY-MM-DD'); - const summariesAxiosPayload: AxiosResponse = await axios.get( - `${items.apiUrl}${items.summariesApiEndPoint}`, - { - params: { - api_key, - end: today, - start: today, - }, - }, - ); - return summariesAxiosPayload.data.data[0].grand_total; - } + if (!this.shouldSendHeartbeat(heartbeat)) return; - /** - * Fetches the api token for logged users in wakatime website - * - * @returns {*} - */ - async fetchApiKey(): Promise { - try { - const items = await browser.storage.sync.get({ - apiUrl: config.apiUrl, - currentUserApiEndPoint: config.currentUserApiEndPoint, - }); - - const apiKeyResponse: AxiosResponse = await axios.post( - `${items.apiUrl}${items.currentUserApiEndPoint}/get_api_key`, - ); - return apiKeyResponse.data.data.api_key; - } catch (err: unknown) { - return ''; + 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 changeExtensionState('ignored'); + console.log(`${url} is on denyList.`); + } + } else if (items.loggingStyle == 'allow') { + const heartbeat = this.getHeartbeat(url, items.allowList as string); + if (heartbeat.url) { + await this.sendHeartbeat( + { + ...heartbeat, + branch: null, + hostname: items.hostname as string, + project: heartbeat.project ?? project, + }, + apiKey, + payload, + ); + } else { + await changeExtensionState('ignored'); + console.log(`${url} is not on allowList.`); + } + } else { + throw Error(`Unknown logging styel: ${items.loggingStyle}`); } } - /** - * Checks if the user is logged in. - * - * @returns {*} - */ - async checkAuth(api_key = ''): Promise { - const items = await browser.storage.sync.get({ - apiUrl: config.apiUrl, - currentUserApiEndPoint: config.currentUserApiEndPoint, - }); - const userPayload: AxiosResponse = await axios.get( - `${items.apiUrl}${items.currentUserApiEndPoint}`, - { params: { api_key } }, - ); - return userPayload.data.data; - } - /** * Depending on various factors detects the current active tab URL or domain, * and sends it to WakaTime for logging. @@ -118,13 +109,13 @@ class WakaTimeCore { return changeExtensionState('notLogging'); } const items = await browser.storage.sync.get({ - blacklist: '', + allowList: '', + denyList: '', hostname: config.hostname, loggingEnabled: config.loggingEnabled, loggingStyle: config.loggingStyle, socialMediaSites: config.socialMediaSites, trackSocialMedia: config.trackSocialMedia, - whitelist: '', }); if (items.loggingEnabled === true) { await changeExtensionState('allGood'); @@ -159,12 +150,12 @@ class WakaTimeCore { const hostname = getDomain(url); if (!items.trackSocialMedia) { if ((items.socialMediaSites as string[]).includes(hostname)) { - return changeExtensionState('blacklisted'); + return changeExtensionState('ignored'); } } // Checks dev websites - const project = generateProjectFromDevSites(url, html); + const project = getHeartbeatFromPage(url, html); // Check if code reviewing const codeReviewing = isCodeReviewing(url); @@ -172,8 +163,8 @@ class WakaTimeCore { payload.category = 'code reviewing'; } - if (items.loggingStyle == 'blacklist') { - if (!contains(url, items.blacklist as string)) { + if (items.loggingStyle == 'deny') { + if (!contains(url, items.denyList as string)) { await this.sendHeartbeat( { branch: null, @@ -185,13 +176,11 @@ class WakaTimeCore { payload, ); } else { - await changeExtensionState('blacklisted'); - console.log(`${url} is on a blacklist.`); + await changeExtensionState('ignored'); + console.log(`${url} is on denyList.`); } - } - - if (items.loggingStyle == 'whitelist') { - const heartbeat = this.getHeartbeat(url, items.whitelist as string); + } else if (items.loggingStyle == 'allow') { + const heartbeat = this.getHeartbeat(url, items.allowList as string); if (heartbeat.url) { await this.sendHeartbeat( { @@ -204,9 +193,11 @@ class WakaTimeCore { payload, ); } else { - await changeExtensionState('whitelisted'); - console.log(`${url} is not on a whitelist.`); + await changeExtensionState('ignored'); + console.log(`${url} is not on allowList.`); } + } else { + throw Error(`Unknown logging styel: ${items.loggingStyle}`); } } } @@ -280,14 +271,14 @@ class WakaTimeCore { * @param debug */ async sendHeartbeat( - heartbeat: SendHeartbeat, + heartbeat: Heartbeat, apiKey: string, navigationPayload: Record, ): Promise { console.log('Sending Heartbeat', heartbeat); let payload; - const loggingType = await this.getLoggingType(); + const loggingType = await getLoggingType(); // Get only the domain from the entity. // And send that in heartbeat if (loggingType == 'domain') { @@ -310,20 +301,6 @@ class WakaTimeCore { } } - /** - * Returns a promise with logging type variable. - * - * @returns {*} - * @private - */ - async getLoggingType(): Promise { - const items = await browser.storage.sync.get({ - loggingType: config.loggingType, - }); - - return items.loggingType; - } - /** * Creates payload for the heartbeat and returns it as JSON. * @@ -333,8 +310,8 @@ class WakaTimeCore { * @returns {*} * @private */ - async preparePayload(heartbeat: SendHeartbeat, type: string): Promise> { - const os = await this.getOperatingSystem(); + async preparePayload(heartbeat: Heartbeat, type: string): Promise> { + const os = await getOperatingSystem(); let browserName = 'chrome'; let userAgent; if (IS_FIREFOX) { @@ -359,14 +336,6 @@ class WakaTimeCore { return payload; } - getOperatingSystem(): Promise { - 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. * diff --git a/src/html/options.html b/src/html/options.html index 81043e6..cf040be 100644 --- a/src/html/options.html +++ b/src/html/options.html @@ -4,7 +4,7 @@ - WakaTime options + WakaTime Options diff --git a/src/types/heartbeats.ts b/src/types/heartbeats.ts index 21fbac2..5ef38a6 100644 --- a/src/types/heartbeats.ts +++ b/src/types/heartbeats.ts @@ -1,37 +1,26 @@ -// 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; - entity: string; - id: string; - is_write: boolean; - language: string; - lineno: null; - lines: number; - machine_name_id: string; - project: string; - time: number; - type: string; - user_agent_id: string; - user_id: string; -} - -export interface SendHeartbeat { +export interface Heartbeat { branch?: string | null; - hostname: string; + category?: Category | null; + entity: string; + entityType: EntityType; + language?: string | null; project?: string | null; - url: string; +} + +export enum Category { + browsing = 'browsing', + code_reviewing = 'code reviewing', + coding = 'coding', + debugging = 'debugging', + designing = 'designing', + meeting = 'meeting', +} + +export enum EntityType { + app = 'app', + domain = 'domain', + file = 'file', + url = 'url', } export interface ProjectDetails { diff --git a/src/types/summaries.ts b/src/types/summaries.ts index 100569f..c711fa7 100644 --- a/src/types/summaries.ts +++ b/src/types/summaries.ts @@ -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; diff --git a/src/utils/changeExtensionState.ts b/src/utils/changeExtensionState.ts index cc40397..19c4aaa 100644 --- a/src/utils/changeExtensionState.ts +++ b/src/utils/changeExtensionState.ts @@ -20,13 +20,9 @@ export default async function changeExtensionState(state: ApiStates): Promise 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 => { + const response = (await browser.tabs.sendMessage(tabId, { message: 'get_html' })) as { + html: string; + }; + return response.html; +}; diff --git a/src/utils/index.ts b/src/utils/index.ts index 0be4a51..cb3cbbe 100644 --- a/src/utils/index.ts +++ b/src/utils/index.ts @@ -1,148 +1,7 @@ -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 => { @@ -154,9 +13,10 @@ export const isCodeReviewing = (url: string): boolean => { return false; }; -export const getHtmlContentByTabId = async (tabId: number): Promise => { - const response = (await browser.tabs.sendMessage(tabId, { message: 'get_html' })) as { - html: string; - }; - return response.html; +export const getOperatingSystem = (): Promise => { + return new Promise((resolve) => { + chrome.runtime.getPlatformInfo(function (info) { + resolve(`${info.os}_${info.arch}`); + }); + }); }; diff --git a/src/utils/logging.ts b/src/utils/logging.ts new file mode 100644 index 0000000..8340f2a --- /dev/null +++ b/src/utils/logging.ts @@ -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 => { + const items = await browser.storage.sync.get({ + loggingType: config.loggingType, + }); + + return items.loggingType; +}; diff --git a/src/utils/settings.ts b/src/utils/settings.ts new file mode 100644 index 0000000..95a0ea2 --- /dev/null +++ b/src/utils/settings.ts @@ -0,0 +1,71 @@ +import browser from 'webextension-polyfill'; +import config, { LoggingStyle, LoggingType, Theme } from '../config/config'; + +export interface Settings { + allowList: string[]; + apiKey: string; + apiUrl: string; + denyList: string[]; + hostname: string; + loggingStyle: LoggingStyle; + loggingType: LoggingType; + socialMediaSites: string[]; + theme: Theme; + trackSocialMedia: boolean; +} + +export const getSettings = async (): Promise => { + 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 & { + blacklist?: string; + socialMediaSites: string[] | string; + whitelist?: string; + }; + + // backwards compatibility + if (typeof settings.whitelist === 'string') { + settings.allowList = settings.whitelist.trim().split('\n'); + await browser.storage.sync.set({ allowList: settings.allowList }); + await browser.storage.sync.remove('whitelist'); + } + if (typeof settings.blacklist === 'string') { + settings.denyList = settings.blacklist.trim().split('\n'); + await browser.storage.sync.set({ denyList: settings.denyList }); + await browser.storage.sync.remove('blacklist'); + } + if (typeof settings.socialMediaSites === 'string') { + settings.socialMediaSites = settings.socialMediaSites.trim().split('\n'); + await browser.storage.sync.set({ + socialMediaSites: settings.socialMediaSites, + }); + } + + return { + allowList: settings.allowList, + apiKey: settings.apiKey, + apiUrl: settings.apiUrl, + denyList: settings.denyList, + hostname: settings.hostname, + loggingStyle: settings.loggingStyle, + loggingType: settings.loggingType, + socialMediaSites: settings.socialMediaSites, + theme: settings.theme, + trackSocialMedia: settings.trackSocialMedia, + }; +}; + +export const saveSettings = async (settings: Settings): Promise => { + return browser.storage.sync.set(settings); +}; diff --git a/src/utils/user.ts b/src/utils/user.ts index 7ef7e55..c95c681 100644 --- a/src/utils/user.ts +++ b/src/utils/user.ts @@ -1,11 +1,31 @@ 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 { GrandTotal, Summaries } from '../types/summaries'; +import { ApiKeyPayload, AxiosUserResponse, User } from '../types/user'; import changeExtensionState from './changeExtensionState'; +/** + * Checks if the user is logged in. + * + * @returns {*} + */ +const checkAuth = async (api_key = ''): Promise => { + const items = await browser.storage.sync.get({ + apiUrl: config.apiUrl, + currentUserApiEndPoint: config.currentUserApiEndPoint, + }); + const userPayload: AxiosResponse = await axios.get( + `${items.apiUrl}${items.currentUserApiEndPoint}`, + { params: { api_key } }, + ); + return userPayload.data.data; +}; + export const logUserIn = async (apiKey: string): Promise => { if (!apiKey) { await changeExtensionState('notSignedIn'); @@ -13,7 +33,7 @@ export const logUserIn = async (apiKey: string): Promise => { } try { - await WakaTimeCore.checkAuth(apiKey); + await checkAuth(apiKey); const items = await browser.storage.sync.get({ loggingEnabled: config.loggingEnabled }); if (items.loggingEnabled === true) { @@ -26,6 +46,47 @@ export const logUserIn = async (apiKey: string): Promise => { } }; +/** + * Fetches the api token for logged users in wakatime website + * + * @returns {*} + */ +const fetchApiKey = async (): Promise => { + try { + const items = await browser.storage.sync.get({ + apiUrl: config.apiUrl, + currentUserApiEndPoint: config.currentUserApiEndPoint, + }); + + const apiKeyResponse: AxiosResponse = 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 => { + const items = await browser.storage.sync.get({ + apiUrl: config.apiUrl, + summariesApiEndPoint: config.summariesApiEndPoint, + }); + + const today = moment().format('YYYY-MM-DD'); + const summariesAxiosPayload: AxiosResponse = 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, @@ -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)); @@ -65,21 +126,6 @@ export const fetchUserData = async ( 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) { - try { - html = await getHtmlContentByTabId(tabId); - // eslint-disable-next-line no-empty - } catch (error: unknown) {} - } - - await WakaTimeCore.recordHeartbeat(html); } catch (err: unknown) { await changeExtensionState('notSignedIn'); } diff --git a/src/wakatimeScript.ts b/src/wakatimeScript.ts index ad22454..f661eea 100644 --- a/src/wakatimeScript.ts +++ b/src/wakatimeScript.ts @@ -1,3 +1,5 @@ +import { getHeartbeatFromPage } from './utils/heartbeat'; + const oneMinute = 60000; const fiveMinutes = 300000; @@ -89,12 +91,8 @@ function debounce(func: () => void, timeout = oneMinute, maxWaitTime = fiveMinut } const sendHeartbeat = debounce(async () => { - const { hostname } = document.location; - - const projectDetails = getParser[hostname]?.(); - if (projectDetails) { - chrome.runtime.sendMessage({ projectDetails, recordHeartbeat: true }); - } + const heartbeat = getHeartbeatFromPage(); + chrome.runtime.sendMessage({ heartbeat: heartbeat, task: 'sendHeartbeat' }); }); chrome.runtime.onMessage.addListener((request: { message: string }, sender, sendResponse) => { diff --git a/tests/utils/contains.spec.ts b/tests/utils/contains.spec.ts index b319869..926e78a 100644 --- a/tests/utils/contains.spec.ts +++ b/tests/utils/contains.spec.ts @@ -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';