Skip to content

A fully open source & end-to-end encrypted note taking alternative to Evernote.

add auto backup support

ammarahm-eda0a3a698f99d
diff --git a/apps/mobile/App.js b/apps/mobile/App.js
index e40790227..91d63695d 100644
--- a/apps/mobile/App.js
+++ b/apps/mobile/App.js
@@ -6,206 +6,225 @@ import {SafeAreaProvider} from 'react-native-safe-area-context';
import {useTracked} from './src/provider';
import {Actions} from './src/provider/Actions';
import {defaultState} from './src/provider/DefaultState';
-import {eSendEvent, eSubscribeEvent, eUnSubscribeEvent, ToastEvent,} from './src/services/EventManager';
-import {eDispatchAction, eOnLoadNote, eResetApp, eStartSyncer,} from './src/utils/Events';
+import {
+ eSendEvent,
+ eSubscribeEvent,
+ eUnSubscribeEvent,
+ ToastEvent,
+} from './src/services/EventManager';
+import {
+ eDispatchAction,
+ eOnLoadNote,
+ eResetApp,
+ eStartSyncer,
+} from './src/utils/Events';
import DeviceInfo from 'react-native-device-info';
import {getNote} from './src/views/Editor/Functions';
import {openEditorAnimation} from './src/utils/Animations';
-import {sleep} from "./src/utils/TimeUtils";
-import {getColorScheme} from "./src/utils/ColorUtils";
-import {getDeviceSize, scale, updateSize} from "./src/utils/SizeUtils";
-import {db} from "./src/utils/DB";
-import {DDS} from "./src/services/DeviceDetection";
-import {MMKV} from "./src/utils/MMKV";
+import {sleep} from './src/utils/TimeUtils';
+import {getColorScheme} from './src/utils/ColorUtils';
+import {getDeviceSize, scale, updateSize} from './src/utils/SizeUtils';
+import {db} from './src/utils/DB';
+import {DDS} from './src/services/DeviceDetection';
+import {MMKV} from './src/utils/mmkv';
+import Backup from './src/services/Backup';
let firstLoad = true;
let note = null;
const App = () => {
- const [, dispatch] = useTracked(), [init, setInit] = useState(false), netInfo = useNetInfo(),
- colorScheme = useColorScheme();
- let I =
- DDS.isTab && !DDS.isSmallTab
- ? require('./index.tablet')
- : require('./index.mobile');
-
- const _onOrientationChange = (o) => {
- let smallTab = DDS.isSmallTab;
- DDS.setNewValues();
- DDS.checkSmallTab(o);
- if (smallTab === DDS.isSmallTab) {
- return;
- }
-
- I =
- DDS.isTab && !DDS.isSmallTab
- ? require('./index.tablet')
- : require('./index.mobile');
-
- setTimeout(() => {
- resetApp();
- }, 1000);
- };
-
+ const [, dispatch] = useTracked(),
+ [init, setInit] = useState(false),
+ netInfo = useNetInfo(),
+ colorScheme = useColorScheme();
+ let I =
+ DDS.isTab && !DDS.isSmallTab
+ ? require('./index.tablet')
+ : require('./index.mobile');
+
+ const _onOrientationChange = (o) => {
+ let smallTab = DDS.isSmallTab;
+ DDS.setNewValues();
+ DDS.checkSmallTab(o);
+ if (smallTab === DDS.isSmallTab) {
+ return;
+ }
- useEffect(() => {
- updateTheme().then(r => r);
- }, [colorScheme]);
-
- const updateTheme = async () => {
- let settings;
- try {
- settings = await MMKV.getStringAsync('settings');
- } catch (e) {
- console.log(e.message);
- } finally {
- if (settings) {
- settings = JSON.parse(settings);
- if (settings.useSystemTheme) {
- let newColors = await getColorScheme(settings.useSystemTheme);
- dispatch({type: Actions.THEME, colors: newColors});
- }
- }
+ I =
+ DDS.isTab && !DDS.isSmallTab
+ ? require('./index.tablet')
+ : require('./index.mobile');
+
+ setTimeout(() => {
+ resetApp();
+ }, 1000);
+ };
+
+ useEffect(() => {
+ updateTheme().then((r) => r);
+ }, [colorScheme]);
+
+ const updateTheme = async () => {
+ let settings;
+ try {
+ settings = await MMKV.getStringAsync('settings');
+ } catch (e) {
+ console.log(e.message);
+ } finally {
+ if (settings) {
+ settings = JSON.parse(settings);
+ if (settings.useSystemTheme) {
+ let newColors = await getColorScheme(settings.useSystemTheme);
+ dispatch({type: Actions.THEME, colors: newColors});
}
- };
+ }
+ }
+ };
- useEffect(() => {
- if (!netInfo.isConnected || !netInfo.isInternetReachable) {
- db.user?.get().then((user) => {
- if (user) {
- ToastEvent.show('No internet connection', 'error');
- } else {
- }
- });
+ useEffect(() => {
+ if (!netInfo.isConnected || !netInfo.isInternetReachable) {
+ db.user?.get().then((user) => {
+ if (user) {
+ ToastEvent.show('No internet connection', 'error');
} else {
- db.user?.get().then((user) => {
- if (user) {
- ToastEvent.show('Internet connection restored', 'success');
- } else {
- }
- });
}
- }, [netInfo]);
-
- const syncChanges = async () => {
- dispatch({type: Actions.ALL});
- }, resetApp = () => {
- note = getNote();
- setInit(false);
- Initialize().then(async () => {
- setInit(true);
- await sleep(300);
- if (note && note.id) {
- eSendEvent(eOnLoadNote, note);
- if (DDS.isPhone || DDS.isSmallTab) {
- openEditorAnimation();
- }
- note = null;
- }
- });
- }, startSyncer = async () => {
- try {
- let user = await db.user.get();
- if (user) {
- db.ev.subscribe('db:refresh', syncChanges);
- }
- } catch (e) {
- console.log(e);
+ });
+ } else {
+ db.user?.get().then((user) => {
+ if (user) {
+ ToastEvent.show('Internet connection restored', 'success');
+ } else {
+ }
+ });
+ }
+ }, [netInfo]);
+
+ const syncChanges = async () => {
+ dispatch({type: Actions.ALL});
+ },
+ resetApp = () => {
+ note = getNote();
+ setInit(false);
+ Initialize().then(async () => {
+ setInit(true);
+ await sleep(300);
+ if (note && note.id) {
+ eSendEvent(eOnLoadNote, note);
+ if (DDS.isPhone || DDS.isSmallTab) {
+ openEditorAnimation();
+ }
+ note = null;
}
+ });
+ },
+ startSyncer = async () => {
+ try {
+ let user = await db.user.get();
+ if (user) {
+ db.ev.subscribe('db:refresh', syncChanges);
+ }
+ } catch (e) {
+ console.log(e);
+ }
};
- useEffect(() => {
- eSubscribeEvent(eStartSyncer, startSyncer);
- eSubscribeEvent(eResetApp, resetApp);
- Orientation.addOrientationListener(_onOrientationChange);
- eSubscribeEvent(eDispatchAction, (type) => {
- dispatch(type);
- });
- return () => {
- db?.ev?.unsubscribe('db:refresh', syncChanges);
- eUnSubscribeEvent(eStartSyncer, startSyncer);
- eUnSubscribeEvent(eResetApp, resetApp);
- eUnSubscribeEvent(eDispatchAction, (type) => {
- dispatch(type);
- });
-
- Orientation.removeOrientationListener(_onOrientationChange);
- };
- }, []);
-
- useEffect(() => {
- let error = null;
- let user;
-
- Initialize().finally(async () => {
- try {
- await db.init();
- user = await db.user.get();
- } catch (e) {
- error = e;
- } finally {
- if (user) {
- dispatch({type: Actions.USER, user: user});
- await startSyncer();
- }
- dispatch({type: Actions.ALL});
-
- setInit(true);
-
- if (error) {
- setTimeout(() => {
- ToastEvent.show(error.message);
- }, 500);
- }
- }
- });
- }, []);
-
- async function Initialize() {
- let settings;
- scale.fontScale = 1;
-
- if (firstLoad) {
- if (DeviceInfo.isTablet() && getDeviceSize() > 9) {
- Orientation.lockToLandscape();
- _onOrientationChange('LANDSCAPE');
- } else {
- Orientation.lockToPortrait();
- }
- firstLoad = false;
+ useEffect(() => {
+ eSubscribeEvent(eStartSyncer, startSyncer);
+ eSubscribeEvent(eResetApp, resetApp);
+ Orientation.addOrientationListener(_onOrientationChange);
+ eSubscribeEvent(eDispatchAction, (type) => {
+ dispatch(type);
+ });
+ return () => {
+ db?.ev?.unsubscribe('db:refresh', syncChanges);
+ eUnSubscribeEvent(eStartSyncer, startSyncer);
+ eUnSubscribeEvent(eResetApp, resetApp);
+ eUnSubscribeEvent(eDispatchAction, (type) => {
+ dispatch(type);
+ });
+
+ Orientation.removeOrientationListener(_onOrientationChange);
+ };
+ }, []);
+
+ useEffect(() => {
+ let error = null;
+ let user;
+
+ Initialize().finally(async () => {
+ try {
+ await db.init();
+ user = await db.user.get();
+ } catch (e) {
+ error = e;
+ } finally {
+ if (user) {
+ dispatch({type: Actions.USER, user: user});
+ await startSyncer();
}
-
- try {
- settings = await MMKV.getStringAsync('settings');
- settings = JSON.parse(settings);
-
- if (settings.fontScale) {
- scale.fontScale = settings.fontScale;
- }
- updateSize();
- } catch (e) {
- if (!settings || !settings.includes('fontScale')) {
- settings = defaultState.settings;
- await MMKV.setStringAsync('settings', JSON.stringify(settings));
- }
- } finally {
- let newColors = await getColorScheme(settings.useSystemTheme);
- dispatch({type: Actions.SETTINGS, settings: {...settings}});
- dispatch({type: Actions.THEME, colors: newColors});
+ dispatch({type: Actions.ALL});
+ setInit(true);
+ sleep(1000).then(async () => {
+ settings = await MMKV.getStringAsync('settings');
+ settings = JSON.parse(settings);
+ if (await Backup.checkBackupRequired(settings.reminder)) {
+ await Backup.run();
+ }
+ });
+ if (error) {
+ setTimeout(() => {
+ ToastEvent.show(error.message);
+ }, 500);
}
+ }
+ });
+ }, []);
+
+ async function Initialize() {
+ let settings;
+ scale.fontScale = 1;
+
+ if (firstLoad) {
+ if (DeviceInfo.isTablet() && getDeviceSize() > 9) {
+ Orientation.lockToLandscape();
+ _onOrientationChange('LANDSCAPE');
+ } else {
+ Orientation.lockToPortrait();
+ }
+ firstLoad = false;
}
- if (!init) {
- return <></>;
+ try {
+ settings = await MMKV.getStringAsync('settings');
+ settings = JSON.parse(settings);
+
+ if (settings.fontScale) {
+ scale.fontScale = settings.fontScale;
+ }
+ updateSize();
+ } catch (e) {
+ if (!settings || !settings.includes('fontScale')) {
+ settings = defaultState.settings;
+ await MMKV.setStringAsync('settings', JSON.stringify(settings));
+ }
+ } finally {
+ let newColors = await getColorScheme(settings.useSystemTheme);
+ dispatch({type: Actions.SETTINGS, settings: {...settings}});
+ dispatch({type: Actions.THEME, colors: newColors});
}
- return (
+ }
+
+ if (!init) {
+ return <></>;
+ }
+ return (
+ <>
+ <SafeAreaProvider>
<>
- <SafeAreaProvider>
- <>
- <I.Initialize/>
- </>
- </SafeAreaProvider>
+ <I.Initialize />
</>
- );
+ </SafeAreaProvider>
+ </>
+ );
};
export default App;
diff --git a/apps/mobile/src/components/RestoreDialog/index.js b/apps/mobile/src/components/RestoreDialog/index.js
index b84dfa3af..fe05e3921 100644
--- a/apps/mobile/src/components/RestoreDialog/index.js
+++ b/apps/mobile/src/components/RestoreDialog/index.js
@@ -45,7 +45,7 @@ const RestoreDialog = () => {
setVisible(false);
};
- const restore = async () => {
+ const restore = async (item,index) => {
if (Platform.OS === 'android') {
let granted = storage.requestPermission();
@@ -62,6 +62,7 @@ const RestoreDialog = () => {
await db.backup.import(backup);
await sleep(2000);
setRestoring(false);
+ console.log(db.notes.all);
dispatch({type: Actions.ALL});
ToastEvent.show('Restore Complete!', 'success');
setVisible(false);
@@ -204,9 +205,9 @@ const RestoreDialog = () => {
</Text>
</View>
}
+ keyExtractor={(item,index) => item.filename}
renderItem={({item, index}) => (
<View
- key={item.filename}
style={{
minHeight: 50,
justifyContent: 'space-between',
@@ -231,7 +232,7 @@ const RestoreDialog = () => {
title="Restore"
width={80}
height={30}
- onPress={restore}
+ onPress={() => restore(item,index)}
/>
</View>
)}
diff --git a/apps/mobile/src/services/Backup.js b/apps/mobile/src/services/Backup.js
new file mode 100644
index 000000000..3923d52dd
--- /dev/null
+++ b/apps/mobile/src/services/Backup.js
@@ -0,0 +1,75 @@
+const {MMKV} = require('../utils/MMKV');
+import RNFetchBlob from 'rn-fetch-blob';
+import storage from '../../utils/storage';
+import {db} from '../utils/DB';
+
+async function run() {
+ if (Platform.OS === 'android') {
+ let granted = await storage.requestPermission();
+ if (!granted) {
+ ToastEvent.show('Backup failed! Storage access was denied.');
+ return;
+ }
+ }
+ let backup;
+ try {
+ backup = await db.backup.export();
+ } catch (e) {
+ console.log('error', e);
+ }
+
+ let backupName = 'notesnook_backup_' + new Date().toString() + '.nnbackup';
+ let path = await storage.checkAndCreateDir('/backups/');
+ await RNFetchBlob.fs.writeFile(path + backupName, backup, 'utf8');
+ await MMKV.setItem('backupDate', JSON.stringify(Date.now()));
+ ToastEvent.show('Backup complete!', 'success');
+ return path;
+}
+
+async function getLastBackupDate() {
+ let date;
+ try {
+ date = await MMKV.getItem('backupDate');
+ } catch (e) {
+ date = 'never';
+ }
+ return date;
+}
+const MS_DAY = 86400000;
+const MS_WEEK = MS_DAY * 7;
+
+async function checkBackupRequired(type) {
+ let now = Date.now();
+ let lastBackupDate = await getLastBackupDate();
+ if (lastBackupDate === 'never') {
+ return true;
+ }
+ lastBackupDate = parseInt(lastBackupDate);
+
+ if (type === 'daily') {
+ now = new Date(now);
+ lastBackupDate = new Date(lastBackupDate);
+ if (now.getUTCDate() > lastBackupDate.getUTCDate()) {
+ return true;
+ } else if (
+ (now.getUTCDate() === lastBackupDate.getUTCDate() &&
+ now.getUTCFullYear() > lastBackupDate.getUTCFullYear()) ||
+ now.getUTCMonth() > lastBackupDate.getUTCMonth()
+ ) {
+ return true;
+ } else {
+ return false;
+ }
+ } else {
+ if (lastBackupDate + MS_WEEK < now) {
+ return true;
+ } else {
+ false;
+ }
+ }
+}
+
+export default {
+ checkBackupRequired,
+ run,
+};
diff --git a/apps/mobile/src/views/Settings/index.js b/apps/mobile/src/views/Settings/index.js
index 07dfb6231..bf7b1ad03 100644
--- a/apps/mobile/src/views/Settings/index.js
+++ b/apps/mobile/src/views/Settings/index.js
@@ -11,7 +11,6 @@ import {
} from 'react-native';
import * as Animatable from 'react-native-animatable';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
-import RNFetchBlob from 'rn-fetch-blob';
import {Button} from '../../components/Button';
import {PressableButton} from '../../components/PressableButton';
import Seperator from '../../components/Seperator';
@@ -19,29 +18,36 @@ import {useTracked} from '../../provider';
import {Actions} from '../../provider/Actions';
import {eSendEvent, ToastEvent} from '../../services/EventManager';
import {
- eCloseProgressDialog,
- eOpenLoginDialog,
- eOpenPremiumDialog,
- eOpenProgressDialog,
- eOpenRecoveryKeyDialog,
- eOpenRestoreDialog,
- eResetApp, eUpdateSearchState,
+ eCloseProgressDialog,
+ eOpenLoginDialog,
+ eOpenPremiumDialog,
+ eOpenProgressDialog,
+ eOpenRecoveryKeyDialog,
+ eOpenRestoreDialog,
+ eResetApp,
+ eUpdateSearchState,
} from '../../utils/Events';
import NavigationService from '../../services/Navigation';
import storage from '../../utils/storage';
+import {setSetting, dWidth} from '../../utils';
+import {hexToRGBA, RGB_Linear_Shade} from '../../utils/ColorUtils';
+import {sleep} from '../../utils/TimeUtils';
import {
- setSetting,
- dWidth,
-} from '../../utils';
-import {hexToRGBA, RGB_Linear_Shade} from "../../utils/ColorUtils";
-import {sleep} from "../../utils/TimeUtils";
-import {ACCENT, COLOR_SCHEME, COLOR_SCHEME_DARK, COLOR_SCHEME_LIGHT, setColorScheme} from "../../utils/Colors";
-import {opacity, pv, SIZE, WEIGHT} from "../../utils/SizeUtils";
-import {db} from "../../utils/DB";
-import {DDS} from "../../services/DeviceDetection";
-import {MMKV} from "../../utils/MMKV";
-
-export const Settings = ({ navigation}) => {
+ ACCENT,
+ COLOR_SCHEME,
+ COLOR_SCHEME_DARK,
+ COLOR_SCHEME_LIGHT,
+ setColorScheme,
+} from '../../utils/Colors';
+import {opacity, pv, SIZE, WEIGHT} from '../../utils/SizeUtils';
+import {db} from '../../utils/DB';
+import {DDS} from '../../services/DeviceDetection';
+import {MMKV} from '../../utils/mmkv';
+import Backup from '../../services/Backup';
+
+
+
+export const Settings = ({navigation}) => {
const [state, dispatch] = useTracked();
const {colors, user, settings} = state;
function changeColorScheme(colors = COLOR_SCHEME, accent = ACCENT) {
@@ -57,27 +63,27 @@ export const Settings = ({ navigation}) => {
}
const onFocus = useCallback(() => {
- dispatch({
- type: Actions.HEADER_STATE,
- state: true,
- });
- dispatch({
- type: Actions.HEADER_TEXT_STATE,
- state: {
- heading: "Settings",
- },
- });
+ dispatch({
+ type: Actions.HEADER_STATE,
+ state: true,
+ });
+ dispatch({
+ type: Actions.HEADER_TEXT_STATE,
+ state: {
+ heading: 'Settings',
+ },
+ });
dispatch({
type: Actions.CURRENT_SCREEN,
screen: 'settings',
});
- eSendEvent(eUpdateSearchState,{
- placeholder:"",
- data: [],
- noSearch: true,
- type: '',
- color: null,
- });
+ eSendEvent(eUpdateSearchState, {
+ placeholder: '',
+ data: [],
+ noSearch: true,
+ type: '',
+ color: null,
+ });
}, []);
useEffect(() => {
@@ -116,32 +122,14 @@ export const Settings = ({ navigation}) => {
{
name: 'Backup data',
func: async () => {
- if (Platform.OS === 'android') {
- let granted = await storage.requestPermission();
- if (!granted) {
- ToastEvent.show('Backup failed! Storage access was denied.');
- return;
- }
- }
eSendEvent(eOpenProgressDialog, {
title: 'Backing up your data',
paragraph:
"All your backups are stored in 'Phone Storage/Notesnook/backups/' folder",
});
- let backup;
- try {
- backup = await db.backup.export();
- } catch (e) {
- console.log('error', e);
- }
-
- let backupName =
- 'notesnook_backup_' + new Date().toString() + '.nnbackup';
- let path = await storage.checkAndCreateDir('/backups/');
- await RNFetchBlob.fs.writeFile(path + backupName, backup, 'utf8');
+ await Backup.run();
await sleep(2000);
eSendEvent(eCloseProgressDialog);
- ToastEvent.show('Backup complete!', 'success');
},
desc: 'Backup all your data to phone storage',
},
@@ -540,7 +528,10 @@ export const Settings = ({ navigation}) => {
await MMKV.setStringAsync('theme', JSON.stringify({night: true}));
changeColorScheme(COLOR_SCHEME_DARK);
} else {
- await MMKV.setStringAsync('theme', JSON.stringify({night: false}));
+ await MMKV.setStringAsync(
+ 'theme',
+ JSON.stringify({night: false}),
+ );
changeColorScheme(COLOR_SCHEME_LIGHT);
}
@@ -790,7 +781,7 @@ export const Settings = ({ navigation}) => {
{
name: 'Privacy Policy',
func: async () => {
- await Linking.openURL('https://www.notesnook.com/privacy.html');
+ await Linking.openURL('https://www.notesnook.com/privacy.html');
},
desc: 'Read our privacy policy',
},