Skip to content

Commit

Permalink
fix: correctly handle urlVariables errors
Browse files Browse the repository at this point in the history
  • Loading branch information
mtdvlpr committed Nov 11, 2024
1 parent 3d8b72a commit de2ec6f
Show file tree
Hide file tree
Showing 17 changed files with 184 additions and 155 deletions.
3 changes: 2 additions & 1 deletion src-electron/main/window/window-base.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { ElectronIpcListenKey } from 'src/types';

import pkg from 'app/package.json';
import { errorCatcher } from 'app/src-electron/utils';
import {
app,
BrowserWindow,
Expand Down Expand Up @@ -131,6 +132,6 @@ export function closeOtherWindows(source: BrowserWindow) {
if (win !== source) win.close();
}
} catch (e) {
console.error(e);
errorCatcher(e);
}
}
5 changes: 3 additions & 2 deletions src-electron/main/window/window-state.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { errorCatcher } from 'app/src-electron/utils';
import {
app,
BrowserWindow,
Expand Down Expand Up @@ -190,7 +191,7 @@ export class StatefulBrowserWindow {
ensureDirSync(dirname(this.fullStoreFileName));
writeJsonSync(this.fullStoreFileName, this.state);
} catch (e) {
console.error(e);
errorCatcher(e);
}
};

Expand Down Expand Up @@ -230,7 +231,7 @@ export class StatefulBrowserWindow {
this.state.displayBounds = display.bounds;
this.state.displayScaleFactor = display.scaleFactor;
} catch (e) {
console.error(e);
errorCatcher(e);
}
};

Expand Down
1 change: 1 addition & 0 deletions src-electron/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ export function errorCatcher(
captureException(error, context);
} else {
console.error(error);
console.warn('context', context);
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/components/dialog/DialogDisplayPopup.vue
Original file line number Diff line number Diff line change
Expand Up @@ -401,7 +401,7 @@ const setMediaBackground = (filepath: string) => {
notifyCustomBackgroundSet();
}
} catch (error) {
console.error(error);
errorCatcher(error);
if (filepath) notifyInvalidBackgroundFile();
mediaWindowCustomBackground.value = '';
} finally {
Expand Down
4 changes: 2 additions & 2 deletions src/components/form-inputs/SelectInput.vue
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
</template>

<script setup lang="ts">
import type { SettingsItemRule } from 'src/types';
import type { SettingsItemRule, SettingsValues } from 'src/types';
import { storeToRefs } from 'pinia';
import { useLocale } from 'src/composables/useLocale';
Expand All @@ -45,7 +45,7 @@ const props = defineProps<{
label?: null | string;
list?: string;
rules?: SettingsItemRule[] | undefined;
settingId?: string;
settingId?: keyof SettingsValues;
useInput?: boolean;
}>();
Expand Down
12 changes: 8 additions & 4 deletions src/components/form-inputs/TextInput.vue
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,11 @@
</template>

<script setup lang="ts">
import type { SettingsItemAction, SettingsItemRule } from 'src/types';
import type {
SettingsItemAction,
SettingsItemRule,
SettingsValues,
} from 'src/types';
import { storeToRefs } from 'pinia';
import { getRules, performActions } from 'src/helpers/settings';
Expand All @@ -45,7 +49,7 @@ const customError = computed(
);
const customFailure = computed(() => {
if (props.settingId?.startsWith('baseUrl')) {
if (props.settingId === 'baseUrl') {
return !urlVariables.value?.mediator;
} else {
return false;
Expand All @@ -55,7 +59,7 @@ const customFailure = computed(() => {
const customSuccess = computed(() => {
if (props.settingId?.startsWith('obs')) {
return obsConnectionState.value === 'connected';
} else if (props.settingId?.startsWith('baseUrl')) {
} else if (props.settingId === 'baseUrl') {
return !!urlVariables.value?.base && !!urlVariables.value?.mediator;
} else {
return false;
Expand All @@ -66,7 +70,7 @@ const props = defineProps<{
actions?: SettingsItemAction[];
label?: null | string;
rules?: SettingsItemRule[];
settingId?: string;
settingId?: keyof SettingsValues;
}>();
const model = defineModel<null | string>({ required: true });
Expand Down
16 changes: 0 additions & 16 deletions src/constants/fonts.ts

This file was deleted.

22 changes: 19 additions & 3 deletions src/helpers/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { errorCatcher } from 'src/helpers/error-catcher';

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const fetchRaw = async (url: string, init?: RequestInit) => {
console.debug('fetchRaw', { init, url });
return fetch(url, init);
};

Expand All @@ -17,18 +18,33 @@ export const fetchJson = async <T>(
params?: URLSearchParams,
): Promise<null | T> => {
try {
if (!url) return null;
const response = await fetchRaw(
`${url}?${params ? params.toString() : ''}`,
);
if (response.ok) {
return response.json();
return await response.json();
} else if (![400, 404].includes(response.status)) {
errorCatcher(response, {
contexts: { fn: { name: 'fetchJson', params, url } },
contexts: {
fn: {
name: 'fetchJson',
params: Object.fromEntries(params || []),
url,
},
},
});
}
} catch (e) {
errorCatcher(e, { contexts: { fn: { name: 'fetchJson', params, url } } });
errorCatcher(e, {
contexts: {
fn: {
name: 'fetchJson',
params: Object.fromEntries(params || []),
url,
},
},
});
}
return null;
};
Expand Down
1 change: 1 addition & 0 deletions src/helpers/error-catcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ const errorCatcher = async (
captureException(originalError, context);
} else {
console.error(originalError);
console.warn('context', context);
}
};

Expand Down
31 changes: 26 additions & 5 deletions src/helpers/fonts.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,44 @@
import type { FontName } from 'src/types';

import { Buffer } from 'buffer';
import { FONT_URLS } from 'src/constants/fonts';
import { useJwStore } from 'src/stores/jw';

import { fetchRaw } from './api';
import { errorCatcher } from './error-catcher';
import { getFontsPath } from './fs';

const { fs, path } = window.electronApi;

export const setElementFont = async (fontName: FontName) => {
if (!fontName) return;

try {
const fontFace = new FontFace(
fontName,
'url("' + (await getLocalFontPath(fontName)) + '")',
);
await fontFace.load();
document.fonts.add(fontFace);
} catch (error) {
const fontFace = new FontFace(
fontName,
'url("' + useJwStore().fontUrls[fontName] + '")',
);
await fontFace.load();
document.fonts.add(fontFace);
errorCatcher(error);
}
};

const getLocalFontPath = async (fontName: FontName) => {
const fontsDir = await getFontsPath();
const fontFileName = `${fontName}.woff2`;
const fontPath = path.join(fontsDir, fontFileName);
let mustDownload = false;
const fontUrls = useJwStore().fontUrls;
try {
if (await fs.exists(fontPath)) {
const headReq = await fetch(FONT_URLS[fontName], {
const headReq = await fetchRaw(fontUrls[fontName], {
method: 'HEAD',
});
if (headReq.ok) {
Expand All @@ -34,7 +57,7 @@ const getLocalFontPath = async (fontName: FontName) => {
}
if (mustDownload) {
await fs.ensureDir(fontsDir);
const response = await fetch(FONT_URLS[fontName], {
const response = await fetchRaw(fontUrls[fontName], {
method: 'GET',
});
if (!response.ok) {
Expand All @@ -46,5 +69,3 @@ const getLocalFontPath = async (fontName: FontName) => {
}
return fontPath;
};

export { getLocalFontPath };
4 changes: 4 additions & 0 deletions src/helpers/jw-media.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1732,6 +1732,10 @@ const setUrlVariables = async (baseUrl: string | undefined) => {
if (attributes['data-pubmedia_url']) {
jwStore.urlVariables.pubMedia = attributes['data-pubmedia_url'];
}

if (!jwStore.urlVariables.mediator || !jwStore.urlVariables.pubMedia) {
resetUrlVariables();
}
} catch (e) {
if (jwStore.urlVariables.base) {
requestControllers
Expand Down
4 changes: 2 additions & 2 deletions src/helpers/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ const getRules = (rules: SettingsItemRule[] | undefined) => {
}
})
.filter((r): r is ValidationRule => !!r) || [];
return filteredRules;
return filteredRules.length ? filteredRules : undefined;
} catch (error) {
errorCatcher(error);
return undefined;
Expand Down Expand Up @@ -134,7 +134,7 @@ const parseJsonSafe = <T>(json: null | string | T, fallback: T): T => {
try {
return typeof json === 'string' ? (JSON.parse(json) as T) : json;
} catch (e) {
console.error(e);
errorCatcher(e);
return fallback;
}
};
Expand Down
26 changes: 7 additions & 19 deletions src/layouts/MainLayout.vue
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ import {
updateLookupPeriod,
} from 'src/helpers/date';
import { errorCatcher } from 'src/helpers/error-catcher';
import { getLocalFontPath } from 'src/helpers/fonts';
import { setElementFont } from 'src/helpers/fonts';
import {
downloadBackgroundMusic,
downloadSongbookVideos,
Expand Down Expand Up @@ -218,9 +218,11 @@ whenever(
watchDebounced(
() => [currentSettings.value?.baseUrl, currentCongregation.value],
([newBaseUrl, newCongregation], [oldBaseUrl, oldCongregation]) => {
if (newBaseUrl !== oldBaseUrl && newCongregation === oldCongregation)
setUrlVariables(newBaseUrl);
async ([newBaseUrl, newCongregation], [oldBaseUrl, oldCongregation]) => {
if (newBaseUrl !== oldBaseUrl && newCongregation === oldCongregation) {
await setUrlVariables(newBaseUrl);
setElementFont('JW-Icons');
}
},
{ debounce: 500 },
);
Expand Down Expand Up @@ -325,20 +327,6 @@ bcClose.onmessage = (event) => {
}
};
const loadJwIconsFont = async () => {
try {
const fontName = 'JW-Icons';
const fontFace = new FontFace(
fontName,
'url("' + (await getLocalFontPath(fontName)) + '")',
);
await fontFace.load();
document.fonts.add(fontFace);
} catch (error) {
errorCatcher(error);
}
};
const initListeners = () => {
window.electronApi.onLog(({ ctx, level, msg }) => {
console[level](`[main] ${msg}`, ctx);
Expand Down Expand Up @@ -401,7 +389,7 @@ onMounted(() => {
if (!currentSettings.value) navigateToCongregationSelector();
// add overflow hidden to body
document.body.style.overflow = 'hidden';
loadJwIconsFont();
setElementFont('JW-Icons');
initListeners();
});
Expand Down
45 changes: 15 additions & 30 deletions src/pages/MediaPlayerPage.vue
Original file line number Diff line number Diff line change
Expand Up @@ -69,15 +69,17 @@
</q-page-container>
</template>
<script setup lang="ts">
import type { FontName } from 'src/types';
import Panzoom, { type PanzoomObject } from '@panzoom/panzoom';
import { useBroadcastChannel, watchDeep, whenever } from '@vueuse/core';
import {
useBroadcastChannel,
watchDeep,
watchImmediate,
whenever,
} from '@vueuse/core';
import { storeToRefs } from 'pinia';
import { useQuasar } from 'quasar';
import { FONT_URLS } from 'src/constants/fonts';
import { errorCatcher } from 'src/helpers/error-catcher';
import { getLocalFontPath } from 'src/helpers/fonts';
import { setElementFont } from 'src/helpers/fonts';
import {
isAudio,
isImage,
Expand All @@ -87,7 +89,7 @@ import {
import { createTemporaryNotification } from 'src/helpers/notifications';
import { useCurrentStateStore } from 'src/stores/current-state';
import { useJwStore } from 'src/stores/jw';
import { computed, onMounted, ref, watch } from 'vue';
import { computed, ref, watch } from 'vue';
const currentState = useCurrentStateStore();
const {
Expand Down Expand Up @@ -379,28 +381,11 @@ $q.iconMapFn = (iconName) => {
}
};
const setElementFont = async (fontName: FontName) => {
if (!fontName) return;
try {
const fontFace = new FontFace(
fontName,
'url("' + (await getLocalFontPath(fontName)) + '")',
);
await fontFace.load();
document.fonts.add(fontFace);
} catch (error) {
const fontFace = new FontFace(
fontName,
'url("' + FONT_URLS[fontName] + '")',
);
await fontFace.load();
document.fonts.add(fontFace);
errorCatcher(error);
}
};
onMounted(() => {
setElementFont('WT-ClearText-Bold');
setElementFont('JW-Icons');
});
watchImmediate(
() => jwStore.urlVariables,
() => {
setElementFont('WT-ClearText-Bold');
setElementFont('JW-Icons');
},
);
</script>
Loading

0 comments on commit de2ec6f

Please sign in to comment.