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

Add error logging and handling for ldb, spotify, sign out #373

Merged
merged 4 commits into from
Jul 6, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
4 changes: 4 additions & 0 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,10 @@ const App = () => {
useEffect(() => {
smoothscroll.polyfill();
if (!keys) {
Sentry.addBreadcrumb({
category: "App.tsx",
message: "Sign Out"
});
signOutAndCleanUp();
} else {
const onboarding = localStorage.getItem("onboarding");
Expand Down
21 changes: 18 additions & 3 deletions src/components/Journal/FinishJournal.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ import ldb from "../../db";
import { InAppReview } from '@capacitor-community/in-app-review';
import Confetti from "react-confetti";
import Dialog, { checkPromptAllowed } from "../Dialog";
import { useLiveQuery } from "dexie-react-hooks";
import { Dialogs } from "./JournalTypes";
import Joyride from "react-joyride";
import SearchSpotify from "./SearchSpotify";
Expand All @@ -28,13 +27,29 @@ const FinishJournal = props => {
const [submitting, setSubmitting] = useState(false);
const [submitted, setSubmitted] = useState(false);
const [dialog, setDialog] = useState(undefined);
const lastLogs = useLiveQuery(() => ldb.logs.orderBy("timestamp").reverse().limit(1).toArray());
const lastAverageLogs = useLiveQuery(() => ldb.logs.orderBy("timestamp").reverse().filter(x => x.average === "average").limit(10).toArray());
const [lastLogs, setLastLogs] = useState(undefined);
const [lastAverageLogs, setLastAverageLogs] = useState(undefined);
const [firstTimer, setFirstTimer] = useState(false);

const dismissDialog = () => {
setDialog(undefined);
};

useEffect(() => {
(async () => {
try {
const logs = await ldb.logs.orderBy("timestamp").reverse().limit(1).toArray();
setLastLogs(logs);

const averageLogs = await ldb.logs.orderBy("timestamp").reverse().filter(x => x.average === "average").limit(10).toArray();
setLastAverageLogs(averageLogs);
} catch (e) {
console.log("Error fetching data from Dexie (caught).");
console.error(e);
Sentry.captureException(e, {tags: {caught: true}});
}
})();
}, []);

useEffect(() => {
// Refresh ID token in the background to speed up submission
Expand Down
18 changes: 10 additions & 8 deletions src/components/Journal/RecordJournal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -98,13 +98,15 @@ const RecordJournal = ({ audioChunks, elapsedTime, setElapsedTime, next, setAudi
audioContext?.close();
audioContext = null;

// Reset visualizer bars
const bars = visualizerRef.current!.children;
for (let i = 0; i < bars.length; i++) {
const elmStyles = (bars[i] as HTMLDivElement).style;
elmStyles.transform = "";
elmStyles.opacity = "";
}
// Reset visualizer bars (if on page)
try {
const bars = visualizerRef.current!.children;
for (let i = 0; i < bars.length; i++) {
const elmStyles = (bars[i] as HTMLDivElement).style;
elmStyles.transform = "";
elmStyles.opacity = "";
}
} catch {}
};

const frequencyData = new Uint8Array(analyser.frequencyBinCount);
Expand All @@ -120,7 +122,7 @@ const RecordJournal = ({ audioChunks, elapsedTime, setElapsedTime, next, setAudi
}
if (!mediaRecorder.current) return;

// Update visualizer
// Update visualizer (if on page)
try {
analyser.getByteFrequencyData(frequencyData);
const bars = visualizerRef.current!.children;
Expand Down
22 changes: 13 additions & 9 deletions src/components/Journal/SearchSpotify.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -57,16 +57,20 @@ const SearchSpotify = ({ user, song, setSong } : Props) => {
const throttleStart = performance.now();
const val = e.detail.value.trim();

const response = await fetch(`${BASE_URL}/spotify/search`, {
method: "POST",
headers: {
"Authorization": `Bearer ${await getIdToken(user)}`,
"Content-Type": "application/json"
},
body: JSON.stringify({ query: val })
}).catch(() => {
let response = undefined;
try {
const token = await getIdToken(user);
response = await fetch(`${BASE_URL}/spotify/search`, {
method: "POST",
headers: {
"Authorization": `Bearer ${token}`,
"Content-Type": "application/json"
},
body: JSON.stringify({ query: val })
})
} catch (e) {
toast("Failed to connect to music search. Are you connected to the Internet?");
});
}

if (response?.ok) {
const data = await response.json();
Expand Down
2 changes: 2 additions & 0 deletions src/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,6 @@ ldb.version(1).stores({
logs: `&timestamp, year, month, day, time, zone, mood, average`,
});

ldb.on("close", () => console.log("db was forcibly closed"));

export default ldb as DB;
13 changes: 13 additions & 0 deletions src/helpers.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { get, orderByKey, query, ref } from "firebase/database";
import Fuse from "fuse.js";
import { murmurhash3_32_gc } from "./murmurhash3_gc";
import UAParser from "ua-parser-js";
import * as Sentry from "@sentry/react";

export interface AnyMap {
[key: string]: any;
Expand Down Expand Up @@ -119,6 +120,10 @@ export function checkKeys() {
const ekeys = decrypt(JSON.parse(localStorage.getItem("ekeys") ?? "{}")["keys"], pwd);
if (!ekeys) {
toast("Something went wrong, please sign in again.");
Sentry.addBreadcrumb({
category: "checkKeys",
message: "Sign Out"
});
signOutAndCleanUp();
return;
}
Expand Down Expand Up @@ -265,6 +270,10 @@ export function encrypt(data: string, key: string) {
return AES.encrypt(data, key).toString();
} catch {
toast("Data encryption failed, so as a security precaution, we ask that you sign in again.");
Sentry.addBreadcrumb({
category: "encrypt",
message: "Sign Out"
});
signOutAndCleanUp();
return "";
}
Expand All @@ -275,6 +284,10 @@ export function decrypt(data: string, key: string, signOut=true) {
return AES.decrypt(data, key).toString(aesutf8);
} catch {
if (signOut) {
Sentry.addBreadcrumb({
category: "decrypt",
message: "Sign Out"
});
toast("Data decryption failed, so as a security precaution, we ask that you sign in again.");
signOutAndCleanUp();
}
Expand Down
5 changes: 5 additions & 0 deletions src/pages/GapFund.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { auth, db, signOutAndCleanUp } from "../firebase";
import { checkKeys, decrypt, goBackSafely, makeRequest, toast } from "../helpers";
import history from "../history";
import Preloader from "./Preloader";
import * as Sentry from "@sentry/react";

interface GapFundData {
email: string;
Expand Down Expand Up @@ -66,6 +67,10 @@ const GapFund = () => {
} else {
if ("data" in data) {
if (!keys) {
Sentry.addBreadcrumb({
category: "GapFund.tsx",
message: "Sign Out"
});
signOutAndCleanUp();
return;
} else if (typeof keys === "string") {
Expand Down
5 changes: 5 additions & 0 deletions src/pages/Journal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { useEffect, useRef, useState } from "react";
import "./Container.css";
import { checkKeys, decrypt } from "../helpers";
import { signOutAndCleanUp } from "../firebase";
import * as Sentry from "@sentry/react";

export interface SpotifySelection {
uri: string;
Expand All @@ -31,6 +32,10 @@ const Journal = () => {
useEffect(() => {
const keys = checkKeys();
if (!keys) {
Sentry.addBreadcrumb({
category: "Journal.tsx",
message: "Sign Out"
});
signOutAndCleanUp();
}

Expand Down
5 changes: 5 additions & 0 deletions src/pages/Login.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { lockClosed, logoApple, logoGoogle } from "ionicons/icons";
import history from "../history";
import { DateTime } from "luxon";
import { FirebaseAnalytics } from "@capacitor-firebase/analytics";
import * as Sentry from "@sentry/react";

enum LoginStates {
START,
Expand Down Expand Up @@ -63,6 +64,10 @@ const Login = ({ setLoggingIn } : { setLoggingIn: (_: boolean) => void }) => {
setLoggingIn(false);
setLoginState(LoginStates.START);
setPassphrase("");
Sentry.addBreadcrumb({
category: "Login.tsx resetFlow",
message: "Sign Out"
});
signOutAndCleanUp();
}

Expand Down
5 changes: 5 additions & 0 deletions src/pages/Settings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { goBackSafely, toast } from "../helpers";
import history from "../history";
import { DateTime } from "luxon";
import ldb from "../db";
import * as Sentry from "@sentry/react";

const Settings = () => {
const [doingAsyncTask, setDoingAsyncTask] = useState(false);
Expand Down Expand Up @@ -102,6 +103,10 @@ const Settings = () => {
role: 'confirm',
handler: () => {
sessionStorage.setItem("deleteAccount", user.uid);
Sentry.addBreadcrumb({
category: "Delete Account",
message: "Sign Out"
});
signOutAndCleanUp();
toast("Sign in again now to delete your account.");
}
Expand Down
9 changes: 9 additions & 0 deletions src/pages/Summary.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { useLiveQuery } from "dexie-react-hooks";
import Preloader from "./Preloader";
import { checkKeys, decrypt, encrypt, parseSettings, setSettings, toast } from "../helpers";
import { FirebaseMessaging } from "@capacitor-firebase/messaging";
import * as Sentry from "@sentry/react";

// Add timestamp to data object, and decrypt as needed
const processNewData = (newData, keys) => {
Expand Down Expand Up @@ -56,6 +57,10 @@ const Summary = () => {
}
const keys = checkKeys();
if (!keys) {
Sentry.addBreadcrumb({
category: "Summary.tsx keys",
message: "Sign Out"
});
signOutAndCleanUp();
}
}, []);
Expand All @@ -74,6 +79,10 @@ const Summary = () => {
const update = parseSettings()["passphraseUpdate"];
if (update !== val && !(!val && !update)) {
toast("Your data protection method has changed elsewhere. To protect your security, we ask that you sign in again.");
Sentry.addBreadcrumb({
category: "Summary.tsx PDP",
message: "Sign Out"
});
signOutAndCleanUp();
}
});
Expand Down