From 2a4457b323f0150016aaf3d945a728b300a54a00 Mon Sep 17 00:00:00 2001 From: Taso Date: Wed, 17 Mar 2021 13:36:42 -0400 Subject: [PATCH] feat(phone/settings): Schema validation & Reset Settings You can now reset your settings to default using the action in the Settings App Setting schema validation has been added that will temporarily reset to default settings if the JSON string contains unexpected values. A alert will pop up informing the user that they should reset to default settings using the action in the settings app, as a permanent solution. --- phone/package.json | 1 + phone/src/Phone.tsx | 17 ++- .../apps/settings/components/SettingsApp.tsx | 32 ++++- phone/src/apps/settings/hooks/useSettings.ts | 110 ++++++++++++++---- phone/src/locale/en.json | 21 ++-- phone/yarn.lock | 5 + 6 files changed, 157 insertions(+), 29 deletions(-) diff --git a/phone/package.json b/phone/package.json index 0ca2763..4dfa4ec 100644 --- a/phone/package.json +++ b/phone/package.json @@ -24,6 +24,7 @@ "enzyme-adapter-react-16": "^1.15.5", "howler": "^2.2.1", "i18next": "^19.7.0", + "jsonschema": "^1.4.0", "parse-url": "^5.0.2", "qs": "^6.9.6", "react": "^16.13.1", diff --git a/phone/src/Phone.tsx b/phone/src/Phone.tsx index da6d5f8..8b94452 100644 --- a/phone/src/Phone.tsx +++ b/phone/src/Phone.tsx @@ -20,7 +20,7 @@ import { useBankService } from './apps/bank/hooks/useBankService'; import { useMessagesService } from './apps/messages/hooks/useMessageService'; import { useNotesService } from './apps/notes/hooks/useNotesService'; import { usePhotoService } from './apps/camera/hooks/usePhotoService'; -import { useSettings } from './apps/settings/hooks/useSettings'; +import { isSettingsSchemaValid, useSettings } from './apps/settings/hooks/useSettings'; import { useCallService } from './os/call/hooks/useCallService'; import { useDialService } from './apps/dialer/hooks/useDialService'; import InjectDebugData from './os/debug/InjectDebugData'; @@ -31,6 +31,7 @@ import { useCallModal } from './os/call/hooks/useCallModal'; import WindowSnackbar from './ui/components/WindowSnackbar'; import { usePhone } from './os/phone/hooks/usePhone'; import { useTranslation } from 'react-i18next'; +import { useSnackbar } from './ui/hooks/useSnackbar'; function Phone() { const { t, i18n } = useTranslation(); @@ -39,12 +40,26 @@ function Phone() { const [settings] = useSettings(); + const { addAlert } = useSnackbar(); + // Set language from local storage // This will only trigger on first mount & settings changes useEffect(() => { i18n.changeLanguage(settings.language.value).catch((e) => console.error(e)); }, [i18n, settings.language]); + useEffect(() => { + if (!isSettingsSchemaValid()) { + addAlert({ + message: t('SETTINGS.MESSAGES.INVALID_SETTINGS'), + type: 'error', + }); + } + // We only want to run this on first mount of the phone, + // so we leave an empty dep array. Otherwise, we hit a max depth error. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); + useNuiService(); useKeyboardService(); usePhoneService(); diff --git a/phone/src/apps/settings/components/SettingsApp.tsx b/phone/src/apps/settings/components/SettingsApp.tsx index 55058c0..0b27fac 100644 --- a/phone/src/apps/settings/components/SettingsApp.tsx +++ b/phone/src/apps/settings/components/SettingsApp.tsx @@ -26,12 +26,14 @@ import { VolumeUp, FileCopy, Book, + DeleteForever, } from '@material-ui/icons'; import { ListSubheader } from '@material-ui/core'; -import { useSettings } from '../hooks/useSettings'; +import { useResetSettings, useSettings } from '../hooks/useSettings'; import { setClipboard } from '../../../os/phone/hooks/useClipboard'; import { useSnackbar } from '../../../ui/hooks/useSnackbar'; +import { IContextMenuOption } from '../../../ui/components/ContextMenu'; const SubHeaderComp = (props: { text: string }) => ( @@ -48,6 +50,8 @@ export const SettingsApp = () => { const { addAlert } = useSnackbar(); + const resetSettings = useResetSettings(); + const handleSettingChange = (key: string | number, value: unknown) => { setSettings({ ...settings, [key]: value }); }; @@ -91,6 +95,23 @@ export const SettingsApp = () => { MapSettingItem(settings.language, (val: SettingOption) => handleSettingChange('language', val)), ); + const handleResetOptions = () => { + resetSettings(); + addAlert({ + message: t('SETTINGS.MESSAGES.SETTINGS_RESET'), + type: 'success', + }); + }; + + const resetSettingsOpts: IContextMenuOption[] = [ + { + selected: false, + onClick: () => handleResetOptions(), + key: 'RESET_SETTINGS', + label: t('SETTINGS.OPTIONS.RESET_SETTINGS'), + }, + ]; + const handleCopyPhoneNumber = () => { setClipboard(simcard.number); addAlert({ @@ -210,6 +231,15 @@ export const SettingsApp = () => { icon={} /> + }> + } + onClick={openMenu} + options={resetSettingsOpts} + /> + diff --git a/phone/src/apps/settings/hooks/useSettings.ts b/phone/src/apps/settings/hooks/useSettings.ts index b99b151..96217ae 100644 --- a/phone/src/apps/settings/hooks/useSettings.ts +++ b/phone/src/apps/settings/hooks/useSettings.ts @@ -1,29 +1,64 @@ -import { atom, DefaultValue, SetterOrUpdater, useRecoilState } from 'recoil'; - +import { atom, DefaultValue, useRecoilState, useResetRecoilState } from 'recoil'; import { SETTINGS_ALL_TWEETS, SETTING_MENTIONS } from '../../../../../typings/twitter'; import config from '../../../config/default.json'; import { SettingOption } from '../../../ui/hooks/useContextMenu'; +import { Schema, Validator } from 'jsonschema'; -const localStorageEffect = (key) => ({ setSelf, onSet }) => { - const savedVal = localStorage.getItem(key); - if (savedVal != null) { - setSelf(JSON.parse(savedVal)); - } +const NPWD_STORAGE_KEY = 'npwd_settings'; - onSet((newValue) => { - if (newValue instanceof DefaultValue) { - localStorage.removeItem(key); - } else { - localStorage.setItem(key, JSON.stringify(newValue)); - } - }); +const v = new Validator(); + +const settingOptionSchema: Schema = { + id: '/SettingOption', + type: 'object', + properties: { + label: { type: 'string' }, + val: { type: 'string' }, + }, + required: true, }; -export const settingsState = atom({ - key: 'settings', - default: config.defaultSettings, - effects_UNSTABLE: [localStorageEffect('npwd_settings')], -}); +const settingsSchema: Schema = { + type: 'object', + properties: { + language: { $ref: '/SettingOption' }, + wallpaper: { $ref: '/SettingOption' }, + frame: { $ref: '/SettingOption' }, + theme: { $ref: '/SettingOption' }, + zoom: { $ref: '/SettingOption' }, + streamerMode: { type: 'boolean' }, + ringtone: { $ref: '/SettingOption' }, + ringtoneVol: { type: 'number' }, + notiSound: { $ref: '/SettingOption' }, + notiSoundVol: { type: 'number' }, + TWITTER_notiFilter: { $ref: '/SettingOption' }, + TWITTER_notiSound: { $ref: '/SettingOption' }, + TWITTER_notiSoundVol: { type: 'number' }, + TWITTER_notifyNewFeedTweet: { type: 'boolean' }, + }, + required: true, +}; + +v.addSchema(settingOptionSchema, '/SettingOption'); + +function isSchemaValid(schema: string): boolean { + const storedSettings = JSON.parse(schema); + const resp = v.validate(storedSettings, settingsSchema); + return resp.valid; +} + +export function isSettingsSchemaValid(): boolean { + const localStore = localStorage.getItem(NPWD_STORAGE_KEY); + if (localStore) { + try { + const parsedSettings = JSON.parse(localStore); + return v.validate(parsedSettings, settingsSchema).valid; + } catch (e) { + console.error('Unable to parse settings JSON', e); + } + } + return true; +} export interface IPhoneSettings { language: SettingOption; @@ -42,6 +77,41 @@ export interface IPhoneSettings { TWITTER_notifyNewFeedTweet: boolean; } -export const useSettings = (): [IPhoneSettings, SetterOrUpdater] => { +const localStorageEffect = (key) => ({ setSelf, onSet }) => { + const savedVal = localStorage.getItem(key); + if (savedVal) { + try { + const validString = !isSchemaValid(savedVal); + if (validString) { + console.error('Settings Schema was invalid, applying default settings'); + setSelf(config.defaultSettings); + } + } catch (e) { + // If we are unable to parse the json string, we set default settings + console.error('Unable to parse JSON'); + setSelf(config.defaultSettings); + } + } + + onSet((newValue) => { + if (newValue instanceof DefaultValue) { + localStorage.removeItem(key); + } else { + localStorage.setItem(key, JSON.stringify(newValue)); + } + }); +}; + +export const settingsState = atom({ + key: 'settings', + default: config.defaultSettings, + effects_UNSTABLE: [localStorageEffect(NPWD_STORAGE_KEY)], +}); + +export const useSettings = () => { return useRecoilState(settingsState); }; + +export const useResetSettings = () => { + return useResetRecoilState(settingsState); +}; diff --git a/phone/src/locale/en.json b/phone/src/locale/en.json index 59754cf..106fdb9 100644 --- a/phone/src/locale/en.json +++ b/phone/src/locale/en.json @@ -3,13 +3,20 @@ "DATE_FORMAT": "MM/DD/YYYY", "DATE_TIME_FORMAT": "MM/DD/YYYY hh:mm A", "SETTINGS": { - "CATEGORY": { - "APPEARANCE": "Appearance", - "PHONE": "Phone" - }, - "OPTIONS": { - "LANGUAGE": "Language" - } + "CATEGORY": { + "APPEARANCE": "Appearance", + "PHONE": "Phone", + "ACTIONS": "Actions" + }, + "OPTIONS": { + "LANGUAGE": "Language", + "RESET_SETTINGS": "Reset Settings", + "RESET_SETTINGS_DESC": "This will clear your locally stored data" + }, + "MESSAGES": { + "INVALID_SETTINGS": "Invalid stored settings! Please reset in the Settings App.", + "SETTINGS_RESET": "Settings have been reset!" + } }, "RELATIVE_TIME": { "future": "in %s", diff --git a/phone/yarn.lock b/phone/yarn.lock index c591689..15ace59 100644 --- a/phone/yarn.lock +++ b/phone/yarn.lock @@ -7917,6 +7917,11 @@ jsonify@~0.0.0: resolved "https://registry.yarnpkg.com/jsonify/-/jsonify-0.0.0.tgz#2c74b6ee41d93ca51b7b5aaee8f503631d252a73" integrity sha1-LHS27kHZPKUbe1qu6PUDYx0lKnM= +jsonschema@^1.4.0: + version "1.4.0" + resolved "https://registry.yarnpkg.com/jsonschema/-/jsonschema-1.4.0.tgz#1afa34c4bc22190d8e42271ec17ac8b3404f87b2" + integrity sha512-/YgW6pRMr6M7C+4o8kS+B/2myEpHCrxO4PEWnqJNBFMjn7EWXqlQ4tGwL6xTHeRplwuZmcAncdvfOad1nT2yMw== + jsprim@^1.2.2: version "1.4.1" resolved "https://registry.yarnpkg.com/jsprim/-/jsprim-1.4.1.tgz#313e66bc1e5cc06e438bc1b7499c2e5c56acb6a2"