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

Feature/43097 - "Export onyx state" button in the troubleshoot section #43552

Merged
merged 24 commits into from
Jul 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
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
3 changes: 3 additions & 0 deletions src/CONST.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,9 @@ const onboardingChoices = {
type OnboardingPurposeType = ValueOf<typeof onboardingChoices>;

const CONST = {
DEFAULT_DB_NAME: 'OnyxDB',
DEFAULT_TABLE_NAME: 'keyvaluepairs',
DEFAULT_ONYX_DUMP_FILE_NAME: 'onyx-state.txt',
DEFAULT_POLICY_ROOM_CHAT_TYPES: [chatTypes.POLICY_ADMINS, chatTypes.POLICY_ANNOUNCE, chatTypes.DOMAIN_ALL],

// Note: Group and Self-DM excluded as these are not tied to a Workspace
Expand Down
2 changes: 2 additions & 0 deletions src/languages/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -958,6 +958,8 @@ export default {
deviceCredentials: 'Device credentials',
invalidate: 'Invalidate',
destroy: 'Destroy',
maskExportOnyxStateData: 'Mask fragile user data while exporting Onyx state',
exportOnyxState: 'Export Onyx state',
},
debugConsole: {
saveLog: 'Save log',
Expand Down
2 changes: 2 additions & 0 deletions src/languages/es.ts
Original file line number Diff line number Diff line change
Expand Up @@ -955,6 +955,8 @@ export default {
deviceCredentials: 'Credenciales del dispositivo',
invalidate: 'Invalidar',
destroy: 'Destruir',
maskExportOnyxStateData: 'Enmascare los datos frágiles del usuario mientras exporta el estado Onyx',
exportOnyxState: 'Exportar estado Onyx',
},
debugConsole: {
saveLog: 'Guardar registro',
Expand Down
34 changes: 34 additions & 0 deletions src/libs/ExportOnyxState/common.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import {Str} from 'expensify-common';
import ONYXKEYS from '@src/ONYXKEYS';

const maskFragileData = (data: Record<string, unknown>, parentKey?: string): Record<string, unknown> => {
const maskedData: Record<string, unknown> = {};

if (!data) {
return maskedData;
}

Object.keys(data).forEach((key) => {
if (!Object.prototype.hasOwnProperty.call(data, key)) {
return;
}

const value = data[key];

if (typeof value === 'string' && (Str.isValidEmail(value) || key === 'authToken' || key === 'encryptedAuthToken')) {
maskedData[key] = '***';
} else if (parentKey && parentKey.includes(ONYXKEYS.COLLECTION.REPORT_ACTIONS) && (key === 'text' || key === 'html')) {
maskedData[key] = '***';
} else if (typeof value === 'object') {
maskedData[key] = maskFragileData(value as Record<string, unknown>, key.includes(ONYXKEYS.COLLECTION.REPORT_ACTIONS) ? key : parentKey);
} else {
maskedData[key] = value;
}
});

return maskedData;
};

export default {
maskFragileData,
};
42 changes: 42 additions & 0 deletions src/libs/ExportOnyxState/index.native.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import RNFS from 'react-native-fs';
import {open} from 'react-native-quick-sqlite';
import Share from 'react-native-share';
import CONST from '@src/CONST';
import common from './common';

const readFromOnyxDatabase = () =>
new Promise((resolve) => {
const db = open({name: CONST.DEFAULT_DB_NAME});
const query = `SELECT * FROM ${CONST.DEFAULT_TABLE_NAME}`;

db.executeAsync(query, []).then(({rows}) => {
// eslint-disable-next-line no-underscore-dangle, @typescript-eslint/no-unsafe-member-access
const result = rows?._array.map((row) => ({[row?.record_key]: JSON.parse(row?.valueJSON as string)}));

resolve(result);
});
});

const shareAsFile = (value: string) => {
try {
// Define new filename and path for the app info file
const infoFileName = CONST.DEFAULT_ONYX_DUMP_FILE_NAME;
const infoFilePath = `${RNFS.DocumentDirectoryPath}/${infoFileName}`;
const actualInfoFile = `file://${infoFilePath}`;

RNFS.writeFile(infoFilePath, value, 'utf8').then(() => {
Share.open({
url: actualInfoFile,
failOnCancel: false,
});
});
} catch (error) {
console.error('Error renaming and sharing file:', error);
}
};

export default {
maskFragileData: common.maskFragileData,
readFromOnyxDatabase,
shareAsFile,
};
50 changes: 50 additions & 0 deletions src/libs/ExportOnyxState/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import CONST from '@src/CONST';
import common from './common';

const readFromOnyxDatabase = () =>
new Promise<Record<string, unknown>>((resolve) => {
let db: IDBDatabase;
const openRequest = indexedDB.open(CONST.DEFAULT_DB_NAME, 1);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should not have had set the default version for database, this caused #45232. Database version was a optional parameter here.

openRequest.onsuccess = () => {
db = openRequest.result;
const transaction = db.transaction(CONST.DEFAULT_TABLE_NAME);
const objectStore = transaction.objectStore(CONST.DEFAULT_TABLE_NAME);
const cursor = objectStore.openCursor();

const queryResult: Record<string, unknown> = {};

cursor.onerror = () => {
console.error('Error reading cursor');
};

cursor.onsuccess = (event) => {
const {result} = event.target as IDBRequest<IDBCursorWithValue>;
if (result) {
queryResult[result.primaryKey as string] = result.value;
result.continue();
} else {
// no results mean the cursor has reached the end of the data
resolve(queryResult);
}
};
};
});

const shareAsFile = (value: string) => {
const element = document.createElement('a');
element.setAttribute('href', `data:text/plain;charset=utf-8,${encodeURIComponent(value)}`);
element.setAttribute('download', CONST.DEFAULT_ONYX_DUMP_FILE_NAME);

element.style.display = 'none';
document.body.appendChild(element);

element.click();

document.body.removeChild(element);
};

export default {
maskFragileData: common.maskFragileData,
readFromOnyxDatabase,
shareAsFile,
};
31 changes: 29 additions & 2 deletions src/pages/settings/Troubleshoot/TroubleshootPage.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, {useMemo, useState} from 'react';
import React, {useCallback, useMemo, useState} from 'react';
import {View} from 'react-native';
import Onyx, {withOnyx} from 'react-native-onyx';
import type {OnyxEntry} from 'react-native-onyx';
Expand All @@ -13,7 +13,9 @@ import MenuItemList from '@components/MenuItemList';
import ScreenWrapper from '@components/ScreenWrapper';
import ScrollView from '@components/ScrollView';
import Section from '@components/Section';
import Switch from '@components/Switch';
import TestToolMenu from '@components/TestToolMenu';
import TestToolRow from '@components/TestToolRow';
import Text from '@components/Text';
import TextLink from '@components/TextLink';
import useEnvironment from '@hooks/useEnvironment';
Expand All @@ -22,6 +24,7 @@ import useTheme from '@hooks/useTheme';
import useThemeStyles from '@hooks/useThemeStyles';
import useWaitForNavigation from '@hooks/useWaitForNavigation';
import useWindowDimensions from '@hooks/useWindowDimensions';
import ExportOnyxState from '@libs/ExportOnyxState';
import Navigation from '@libs/Navigation/Navigation';
import * as App from '@userActions/App';
import * as Report from '@userActions/Report';
Expand Down Expand Up @@ -52,6 +55,18 @@ function TroubleshootPage({shouldStoreLogs}: TroubleshootPageProps) {
const waitForNavigate = useWaitForNavigation();
const {isSmallScreenWidth} = useWindowDimensions();
const illustrationStyle = getLightbulbIllustrationStyle();
const [shouldMaskOnyxState, setShouldMaskOnyxState] = useState(true);

const exportOnyxState = useCallback(() => {
ExportOnyxState.readFromOnyxDatabase().then((value: Record<string, unknown>) => {
let dataToShare = value;
if (shouldMaskOnyxState) {
dataToShare = ExportOnyxState.maskFragileData(value);
}

ExportOnyxState.shareAsFile(JSON.stringify(dataToShare));
});
}, [shouldMaskOnyxState]);

const menuItems = useMemo(() => {
const debugConsoleItem: BaseMenuItem = {
Expand All @@ -66,6 +81,11 @@ function TroubleshootPage({shouldStoreLogs}: TroubleshootPageProps) {
icon: Expensicons.RotateLeft,
action: () => setIsConfirmationModalVisible(true),
},
{
translationKey: 'initialSettingsPage.troubleshoot.exportOnyxState',
icon: Expensicons.Download,
action: exportOnyxState,
},
];

if (shouldStoreLogs) {
Expand All @@ -81,7 +101,7 @@ function TroubleshootPage({shouldStoreLogs}: TroubleshootPageProps) {
wrapperStyle: [styles.sectionMenuItemTopDescription],
}))
.reverse();
}, [shouldStoreLogs, translate, waitForNavigate, styles.sectionMenuItemTopDescription]);
}, [waitForNavigate, exportOnyxState, shouldStoreLogs, translate, styles.sectionMenuItemTopDescription]);

return (
<ScreenWrapper
Expand Down Expand Up @@ -122,6 +142,13 @@ function TroubleshootPage({shouldStoreLogs}: TroubleshootPageProps) {
<View style={[styles.flex1, styles.mt5]}>
<View>
<ClientSideLoggingToolMenu />
<TestToolRow title={translate('initialSettingsPage.troubleshoot.maskExportOnyxStateData')}>
<Switch
accessibilityLabel={translate('initialSettingsPage.troubleshoot.maskExportOnyxStateData')}
isOn={shouldMaskOnyxState}
onToggle={setShouldMaskOnyxState}
/>
</TestToolRow>
</View>
<MenuItemList
menuItems={menuItems}
Expand Down
Loading