Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: allow manually configuring the browser name #154

Merged
merged 5 commits into from
Feb 9, 2025
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions src/background/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import config from '../config'

import { AWClient, IEvent } from 'aw-client'
import retry from 'p-retry'
import { emitNotification, getBrowserName, logHttpError } from './helpers'
import { emitNotification, getBrowser, logHttpError } from './helpers'
import { getSyncStatus, setSyncStatus } from '../storage'

export const getClient = () =>
Expand Down Expand Up @@ -65,4 +65,7 @@ export async function sendHeartbeat(
})
}

export const getBucketId = () => `aw-watcher-web-${getBrowserName()}`
export const getBucketId = async (): Promise<string> => {
const browser = await getBrowser()
return `aw-watcher-web-${browser}`
}
4 changes: 2 additions & 2 deletions src/background/heartbeat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ async function heartbeat(
console.debug('Sending heartbeat for previous data', previousData)
await sendHeartbeat(
client,
getBucketId(),
await getBucketId(),
new Date(now.getTime() - 1),
previousData,
config.heartbeat.intervalInSeconds + 20,
Expand All @@ -46,7 +46,7 @@ async function heartbeat(
console.debug('Sending heartbeat', data)
await sendHeartbeat(
client,
getBucketId(),
await getBucketId(),
now,
data,
config.heartbeat.intervalInSeconds + 20,
Expand Down
15 changes: 14 additions & 1 deletion src/background/helpers.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import browser from 'webextension-polyfill'
import { FetchError } from 'aw-client'
import { getBrowserName, setBrowserName } from '../storage'

export const getTab = (id: number) => browser.tabs.get(id)
export const getTabs = (query: browser.Tabs.QueryQueryInfoType = {}) =>
Expand All @@ -23,8 +24,20 @@ export function emitNotification(title: string, message: string) {
})
}

export const getBrowser = async (): Promise<string> => {
const storedName = await getBrowserName()
if (storedName) {
return storedName
}

const browserName = detectBrowser()

await setBrowserName(browserName)
return browserName
}

// FIXME: Detect Vivaldi? It seems to be intentionally impossible
export const getBrowserName = () => {
export const detectBrowser = () => {
if ((navigator as any).brave?.isBrave()) {
return 'brave'
} else if (
Expand Down
4 changes: 4 additions & 0 deletions src/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@
"{{firefox}}.persistent": true
},

"options_ui": {
"page": "src/settings/index.html"
},

"{{firefox}}.permissions": [
"tabs",
"alarms",
Expand Down
10 changes: 10 additions & 0 deletions src/popup/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,16 @@
<!-- Filled by JS -->
</td>
</tr>

<tr>
<th align="right">Browser:</th>
<td>
<code id="status-browser">
<!-- Filled by JS -->
</code>
<button id="edit-btn">✎</button>
</td>
</tr>
</table>

<hr />
Expand Down
15 changes: 15 additions & 0 deletions src/popup/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
setEnabled,
watchSyncDate,
watchSyncSuccess,
getBrowserName,
} from '../storage'

function setConnected(connected: boolean | undefined) {
Expand All @@ -31,6 +32,7 @@ async function renderStatus() {
const enabled = await getEnabled()
const syncStatus = await getSyncStatus()
const consentStatus = await getConsentStatus()
const browserName = await getBrowserName()

// Enabled checkbox
const enabledCheckbox = document.getElementById('status-enabled-checkbox')
Expand Down Expand Up @@ -72,6 +74,11 @@ async function renderStatus() {
if (!(webuiLink instanceof HTMLAnchorElement))
throw Error('Web UI link is not an anchor')
webuiLink.href = baseUrl ?? '#'

const browserNameElement = document.getElementById('status-browser')
if (!(browserNameElement instanceof HTMLElement))
throw Error('Browser name element is not defined')
browserNameElement.innerText = browserName
}

function domListeners() {
Expand All @@ -82,13 +89,21 @@ function domListeners() {
const enabled = enabledCheckbox.checked
setEnabled(enabled)
})

const consentButton = document.getElementById('status-consent-btn')!
consentButton.addEventListener('click', () => {
browser.tabs.create({
active: true,
url: browser.runtime.getURL('src/consent/index.html'),
})
})

const browserButton = document.getElementById('edit-btn')
if (!(browserButton instanceof HTMLButtonElement))
throw Error('Edit button is not a button')
browserButton.addEventListener('click', () => {
browser.runtime.openOptionsPage()
})
}

renderStatus()
Expand Down
8 changes: 8 additions & 0 deletions src/popup/style.css
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,11 @@ button {
#status-consent-btn {
display: none;
}

form {
margin: 0 0.5em;
}

label {
font-weight: bold;
}
42 changes: 42 additions & 0 deletions src/settings/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>ActivityWatch settings</title>
<link href="./style.css" rel="stylesheet" type="text/css" />
</head>

<body>
<form>
<label for="browser">
<strong>Browser:</strong>
</label>

<select id="browser" name="browser">
<option value="chrome">Chrome</option>
<option value="firefox">Firefox</option>
<option value="opera">Opera</option>
<option value="brave">Brave</option>
<option value="edge">Edge</option>
<option value="arc">Arc</option>
<option value="vivaldi">Vivaldi</option>
<option value="orion">Orion</option>
<option value="yandex">Yandex</option>
<option value="other">Other...</option>
</select>

<input
type="text"
id="customBrowser"
name="customBrowser"
pattern="[a-z]*"
ErikBjare marked this conversation as resolved.
Show resolved Hide resolved
placeholder="Custom browser name"
required
BelKed marked this conversation as resolved.
Show resolved Hide resolved
/>

<button type="submit" class="accept">Save</button>
</form>

<script src="./main.js"></script>
</body>
</html>
93 changes: 93 additions & 0 deletions src/settings/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import browser from 'webextension-polyfill'
import { getBrowserName, setBrowserName } from '../storage'

interface HTMLElementEvent<T extends HTMLElement> extends Event {
target: T
}

async function reloadExtension(): Promise<void> {
browser.runtime.reload()
}

async function saveOptions(e: SubmitEvent): Promise<void> {
e.preventDefault()

const browserSelect = document.querySelector<HTMLSelectElement>('#browser')
const customBrowserInput =
document.querySelector<HTMLInputElement>('#customBrowser')
if (!browserSelect) return

let selectedBrowser = browserSelect.value
if (selectedBrowser === 'other' && customBrowserInput?.value) {
selectedBrowser = customBrowserInput.value.toLowerCase()
}

const form = e.target as HTMLFormElement
const button = form.querySelector<HTMLButtonElement>('button')
if (!button) return

button.textContent = 'Saving...'
button.classList.remove('accept')

try {
await setBrowserName(selectedBrowser)
await reloadExtension()
button.textContent = 'Save'
button.classList.add('accept')
} catch (error) {
console.error('Failed to save options:', error)
button.textContent = 'Error'
button.classList.add('error')
}
}

function toggleCustomBrowserInput(): void {
const browserSelect = document.querySelector<HTMLSelectElement>('#browser')
const customInput = document.querySelector<HTMLInputElement>('#customBrowser')

if (browserSelect && customInput) {
const isOther = browserSelect.value === 'other'
customInput.style.display = isOther ? 'block' : 'none'
customInput.required = isOther
}
}

async function restoreOptions(): Promise<void> {
try {
const browserName = await getBrowserName()
const browserSelect = document.querySelector<HTMLSelectElement>('#browser')
const customInput =
document.querySelector<HTMLInputElement>('#customBrowser')

if (!browserSelect || !customInput || !browserName) return

const standardBrowsers = Array.from(browserSelect.options).map(
(opt) => opt.value,
)
if (!standardBrowsers.includes(browserName)) {
browserSelect.value = 'other'
customInput.style.display = 'block'
customInput.value = browserName
customInput.required = true
} else {
browserSelect.value = browserName
customInput.style.display = 'none'
customInput.required = false
}
} catch (error) {
console.error('Failed to restore options:', error)
}
}

document.addEventListener('DOMContentLoaded', () => {
restoreOptions()
toggleCustomBrowserInput()
})

document
.querySelector('#browser')
?.addEventListener('change', toggleCustomBrowserInput)
const form = document.querySelector('form')
if (form) {
form.addEventListener('submit', saveOptions as EventListener)
}
14 changes: 14 additions & 0 deletions src/settings/style.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
body {
font-family: 'Segoe UI', 'Lucida Grande', Tahoma, sans-serif;
}

form {
display: flex;
gap: 10px;
align-items: center;
margin: 0.5em;
}

#customBrowser {
display: none;
}
6 changes: 6 additions & 0 deletions src/storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,3 +84,9 @@ export const getHeartbeatData = (): Promise<HeartbeatData | undefined> =>
.then((_) => _.heartbeatData as HeartbeatData | undefined)
export const setHeartbeatData = (heartbeatData: HeartbeatData) =>
browser.storage.local.set({ heartbeatData })

type BrowserName = string
export const getBrowserName = (): Promise<BrowserName | undefined> =>
browser.storage.local.get('browserName').then((_) => _.browserName)
export const setBrowserName = (browserName: BrowserName) =>
browser.storage.local.set({ browserName })