Skip to content

Commit

Permalink
update logging, remove onInstall event - ms
Browse files Browse the repository at this point in the history
  • Loading branch information
mlsof21 committed Oct 7, 2023
1 parent ab169d0 commit f76c91f
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 43 deletions.
15 changes: 6 additions & 9 deletions src/ts/background.ts
@@ -1,7 +1,8 @@
import { infoLog } from './common';
const tag = 'background';

chrome.commands.onCommand.addListener((command: any) => {
infoLog('voice dim', `Command "${command}" triggered`);
infoLog(tag, `Command "${command}" triggered`);
sendDimTabMessage({ dimShortcutPressed: true });
});

Expand All @@ -23,30 +24,26 @@ async function getDimTabId(): Promise<number | undefined | null> {
async function sendDimTabMessage(message: any) {
const dimTabId = await getDimTabId();
if (dimTabId) {
infoLog('message', 'sending', message);
infoLog(tag, 'sending', message);

chrome.tabs.sendMessage(dimTabId, message, (response: any) => {
infoLog('voice dim', { response });
infoLog(tag, { response });
});
}
}

chrome.runtime.onMessage.addListener((data: any, sender: chrome.runtime.MessageSender) => {
infoLog('voice dim', { data });
infoLog(tag, { data });
if (data === 'showOptions') {
openOptionsPage();
}
});

chrome.runtime.onInstalled.addListener(() => {
openOptionsPage();
});

async function openOptionsPage() {
const [optionsTab] = await chrome.tabs.query({
url: `chrome-extension://${chrome.runtime.id}\/html\/options.html`,
});
infoLog('voice dim', { optionsTab });
infoLog(tag, { optionsTab });
if (!optionsTab) chrome.tabs.create({ url: '../html/options.html' });
else {
chrome.tabs.update(optionsTab.id!, { active: true });
Expand Down
14 changes: 8 additions & 6 deletions src/ts/common.ts
@@ -1,18 +1,20 @@
export const logs: Log[] = [];

const commonTag = 'common';

export type Log = {
tag: string;
message: unknown;
args: unknown[];
};

export function infoLog(tag: string, message: unknown, ...args: unknown[]) {
console.log(`[${tag}]`, message, ...args);
console.log(`[voice dim - ${tag}]`, message, ...args);
logs.push({ tag: `[${tag} info]`, message, args });
}

export function debugLog(tag: string, message: unknown, ...args: unknown[]) {
console.debug(`[${tag}]`, message, ...args);
console.debug(`[voice dim - ${tag}]`, message, ...args);
logs.push({ tag: `[${tag} debug]`, message, args });
}

Expand Down Expand Up @@ -71,7 +73,7 @@ export async function waitForElementToDisplay(
} else {
setTimeout(function () {
if (timeoutInMs && Date.now() - startTimeInMs > timeoutInMs) {
debugLog('voice dim', "couldn't find", selector);
debugLog(commonTag, "couldn't find", selector);
return reject();
}
loopSearch();
Expand Down Expand Up @@ -104,7 +106,7 @@ export const DEFAULT_ALWAYS_LISTENING: AlwaysListening = {

export function store<T>(key: string, value: T) {
chrome.storage.local.set({ [key]: value }, () => {
infoLog('voice dim', 'Stored', key, value);
infoLog(commonTag, 'Stored', key, value);
});
}

Expand All @@ -115,12 +117,12 @@ export function retrieve<T>(key: string, defaultValue: T): Promise<T> {
console.error(chrome.runtime.lastError.message);
reject(chrome.runtime.lastError.message);
}
infoLog('voice dim', { result });
infoLog(commonTag, { result });
if (Object.keys(result).length == 0) {
store(key, defaultValue);
resolve(defaultValue);
}
infoLog('voice dim', 'Found', result[key]);
infoLog(commonTag, 'Found', result[key]);
resolve(result[key]);
});
});
Expand Down
14 changes: 8 additions & 6 deletions src/ts/options.ts
Expand Up @@ -10,6 +10,8 @@ import {
store,
} from './common';

const tag = 'options';

function onCommandChange() {
const commands: Record<string, string[]> = {};
Object.keys(DEFAULT_COMMANDS).forEach((command) => {
Expand All @@ -24,7 +26,7 @@ function onCommandChange() {
const dimTabs = tabs.filter((tab) => tab.url?.match(/destinyitemmanager\.com.*inventory/));
if (dimTabs && dimTabs[0].id)
chrome.tabs.sendMessage(dimTabs[0].id, 'shortcut updated', (response) => {
infoLog('voice dim', { response });
infoLog(tag, { response });
});
});
}
Expand All @@ -34,13 +36,13 @@ function sendListenOptionsMessage() {
const dimTab = tabs.filter((tab) => tab.url?.match(/destinyitemmanager\.com.*inventory/))[0];
if (dimTab.id)
chrome.tabs.sendMessage(dimTab.id, 'listening options updated', (response) => {
infoLog('voice dim', { response });
infoLog(tag, { response });
});
});
}

function onActivationPhraseChange() {
infoLog('voice dim', 'updating activation phrase');
infoLog(tag, 'updating activation phrase');

const activationPhrase = <HTMLInputElement>document.getElementById('activationPhrase');
const listeningToggle = <HTMLInputElement>document.getElementById('alwaysListeningToggle');
Expand All @@ -56,7 +58,7 @@ function onActivationPhraseChange() {
}

function onAlwaysListeningChange(listeningOptions: AlwaysListening) {
infoLog('voice dim', 'updating alwaysListening');
infoLog(tag, 'updating alwaysListening');

updateSaveText(true, 'Saved!');
setTimeout(() => updateSaveText(false), 3000);
Expand Down Expand Up @@ -115,7 +117,7 @@ function downloadLogsButtonClicked() {
const dimTabs = tabs.filter((tab) => tab.url?.match(/destinyitemmanager\.com.*inventory/));
if (dimTabs && dimTabs[0].id)
chrome.tabs.sendMessage(dimTabs[0].id, 'get logs', (response: { ack: string; logs: Log[] }) => {
infoLog('voice dim', { response });
infoLog(tag, { response });
const { logs } = response;

createDownloadableFile(transformLogs(logs));
Expand Down Expand Up @@ -156,7 +158,7 @@ window.onload = function () {
const activationPhraseInput = <HTMLInputElement>document.getElementById('activationPhrase');
activationPhraseInput?.addEventListener('keydown', debounce(onActivationPhraseChange));
const commandInputs = document.querySelectorAll('.commands input');
infoLog('voice dim', { commandInputs });
infoLog(tag, { commandInputs });
commandInputs.forEach((input) => {
input.addEventListener('keydown', debounce(onCommandChange));
});
Expand Down
45 changes: 23 additions & 22 deletions src/ts/voiceDim.ts
Expand Up @@ -15,6 +15,7 @@ import {

const annyang = require('annyang');

const tag = 'main';
// Keyboard and Mouse Events
const uiEvents = {
singleClick: new MouseEvent('click', {
Expand Down Expand Up @@ -192,12 +193,12 @@ async function parseSpeech(this: any, transcript: string) {
const closestMatch = getClosestMatch(Object.keys(mappedCommands), query);

if (!closestMatch) {
infoLog('voice dim', "Couldn't determine correct action");
infoLog(tag, "Couldn't determine correct action");
return;
}
const closestAction = getClosestMatch(Object.keys(potentialActions), mappedCommands[closestMatch.match]);
if (!closestAction) {
infoLog('voice dim', "Couldn't determine correct action");
infoLog(tag, "Couldn't determine correct action");
return;
}

Expand Down Expand Up @@ -244,9 +245,9 @@ function getCurrentCharacterClass(): string {
return '';
}
async function handleItemMovement(query: string, action: string): Promise<void> {
infoLog('voice dim', 'in handleItemMovement', { query, action });
infoLog(tag, 'in handleItemMovement', { query, action });
const itemToMove = await getItemToMove(query);
debugLog('voice dim', { itemToMove });
debugLog(tag, { itemToMove });
if (!itemToMove) {
await clearSearchBar();
return;
Expand Down Expand Up @@ -277,7 +278,7 @@ async function getItemToMove(query: string): Promise<Element | null> {
const itemToGet = getClosestMatch(Object.keys(availableItems), splitQuery[0]);
if (!itemToGet) return null;
const fullName = availableItems[itemToGet.match].name;
debugLog('voice dim', { itemToGet });
debugLog(tag, { itemToGet });
await populateSearchBar(`${perkQuery} name:"${fullName}"`.trim());
const visibleItems = getVisibleItems();
itemToMove = visibleItems[0];
Expand Down Expand Up @@ -344,7 +345,7 @@ function getPerkQuery(query: string) {
}

async function handleStartFarmingMode() {
infoLog('voice dim', 'Starting farming mode');
infoLog(tag, 'Starting farming mode');
await openCurrentCharacterLoadoutMenu();
const farmingSpan = document.querySelector('.loadout-menu ul li span');
farmingSpan?.dispatchEvent(uiEvents.singleClick);
Expand Down Expand Up @@ -375,7 +376,7 @@ async function openCurrentCharacterLoadoutMenu() {
}

async function handleEquipLoadout(loadoutName: string) {
infoLog('voice dim', 'Equipping loadout', loadoutName);
infoLog(tag, 'Equipping loadout', loadoutName);
await openCurrentCharacterLoadoutMenu();
const availableLoadoutNames = getLoadoutNames();
const loadoutToEquip = getClosestMatch(availableLoadoutNames, loadoutName);
Expand Down Expand Up @@ -444,18 +445,18 @@ function getClosestMatch(availableItems: string[], query: string): FuseMatch | n
};
const fuse = new Fuse(availableItems, options);
const result = fuse.search(query);
debugLog('voice dim', { result, query });
debugLog(tag, { result, query });

if (isAcceptableResult(result)) {
return { toReplace: query, match: result[0].item };
}

debugLog('voice dim', "Couldn't find a match. Trying to find match by splitting the current query.");
debugLog(tag, "Couldn't find a match. Trying to find match by splitting the current query.");
const splitQuery = query.split(' ');

for (const split of splitQuery) {
const splitResult = fuse.search(split);
debugLog('voice dim', { splitResult, split });
debugLog(tag, { splitResult, split });
return isAcceptableResult(splitResult)
? { toReplace: split, match: splitResult[0].item }
: { toReplace: '', match: '' };
Expand All @@ -474,7 +475,7 @@ async function populateSearchBar(searchInput: string): Promise<void> {
const count = getVisibleItems().length;
const newValue = `${searchBar.value} ${searchInput.trim()}`.trim();
searchBar.value = newValue;
infoLog('voice dim', 'Populating search bar with', searchBar.value);
infoLog(tag, 'Populating search bar with', searchBar.value);
await simulateSearchInput();

await waitForSearchToUpdate(count);
Expand All @@ -490,7 +491,7 @@ async function simulateSearchInput() {
}

async function clearSearchBar() {
infoLog('voice dim', 'Clearing search bar');
infoLog(tag, 'Clearing search bar');
const clearButton = document.querySelector('.filter-bar-button[title^=Clear]');
const initialCount = getVisibleItems().length;
let waitForUpdate = false;
Expand Down Expand Up @@ -528,9 +529,9 @@ function updateMicIcon(newMode: string) {

function initializeShortcutListening() {
annyang.addCallback('result', (userSaid: string[]) => {
debugLog('shortcut', userSaid);
debugLog(`${tag} shortcut`, userSaid);
const transcript = userSaid[0].trim().toLowerCase();
infoLog('voice dim', 'Heard', transcript);
infoLog(tag, 'Heard', transcript);
updateUiTranscript(transcript, true);
parseSpeech(transcript);
updateMicIcon('notListening');
Expand All @@ -544,7 +545,7 @@ function initializeShortcutListening() {
function initializeAlwaysListening() {
annyang.start({ autoRestart: listeningOptions.active, continuous: listeningOptions.active });
annyang.addCallback('result', (userSaid?: string[] | undefined) => {
debugLog('voice dim', { userSaid });
debugLog(tag, { userSaid });
if (userSaid) {
let actionPerformed = false;
for (let said of userSaid) {
Expand All @@ -558,7 +559,7 @@ function initializeAlwaysListening() {
// include a space intentionally
if (said.includes(`${phrase} `)) {
const transcript = said.split(`${phrase} `)[1];
infoLog('voice dim', 'Heard', transcript);
infoLog(tag, 'Heard', transcript);
updateUiTranscript(transcript, true);
parseSpeech(transcript);
actionPerformed = true;
Expand All @@ -573,7 +574,7 @@ function initializeAlwaysListening() {
}

chrome.runtime.onMessage.addListener(async function (request, sender, sendResponse) {
infoLog('voice dim', 'Message received', { request });
infoLog(tag, 'Message received', { request });
if (request.dimShortcutPressed && !listeningOptions.active) {
handleShortcutPress();
}
Expand All @@ -584,11 +585,11 @@ chrome.runtime.onMessage.addListener(async function (request, sender, sendRespon
await getAlwaysListeningOptions();
}
if (request === 'not on inventory page') {
infoLog('voice dim', 'no longer on inventory page');
infoLog(tag, 'no longer on inventory page');
stopVoiceDim();
}
if (request === 'on inventory page') {
infoLog('voice dim', 'on inventory page');
infoLog(tag, 'on inventory page');
init();
}
if (request === 'get logs') {
Expand All @@ -604,7 +605,7 @@ chrome.runtime.onMessage.addListener(async function (request, sender, sendRespon
async function getCustomCommands() {
const commands = await retrieve('commands', DEFAULT_COMMANDS);
mappedCommands = reverseMapCustomCommands(commands);
infoLog('voice dim', { commands, mappedCommands });
infoLog(tag, { commands, mappedCommands });
}

function reverseMapCustomCommands(commands: Record<string, string[]>) {
Expand All @@ -620,7 +621,7 @@ function reverseMapCustomCommands(commands: Record<string, string[]>) {

async function getAlwaysListeningOptions() {
listeningOptions = await retrieve('alwaysListening', DEFAULT_ALWAYS_LISTENING);
infoLog('voice dim', { listeningOptions });
infoLog(tag, { listeningOptions });
startListening();
// annyang.debug(true);
}
Expand Down Expand Up @@ -678,7 +679,7 @@ async function getPerks() {
'https://raw.githubusercontent.com/DestinyItemManager/d2ai-module/master/voice-dim-valid-perks.json'
);
knownPerks = await response.json();
infoLog('voice dim', { knownPerks });
infoLog(tag, { knownPerks });
}

function init() {
Expand Down

0 comments on commit f76c91f

Please sign in to comment.