Skip to content

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

feat: migrate backup and restore to scoped storage

ammarahm-ed8897d23be3a1
diff --git a/apps/mobile/src/components/Dialog/DialogHeader.js b/apps/mobile/src/components/Dialog/DialogHeader.js
index 350b7c272..2e117ef4f 100644
--- a/apps/mobile/src/components/Dialog/DialogHeader.js
+++ b/apps/mobile/src/components/Dialog/DialogHeader.js
@@ -17,17 +17,17 @@ const DialogHeader = ({icon, title, paragraph, button, paragraphColor}) => {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
- minHeight: 50,
+ minHeight: 50
}}>
<View
style={{
- width: '100%',
+ width: '100%'
}}>
<View
style={{
flexDirection: 'row',
justifyContent: 'space-between',
- alignItems: 'center',
+ alignItems: 'center'
}}>
<Heading size={SIZE.xl}>{title}</Heading>
@@ -36,10 +36,11 @@ const DialogHeader = ({icon, title, paragraph, button, paragraphColor}) => {
onPress={button.onPress}
style={{
borderRadius: 100,
+ paddingHorizontal: 12
}}
fontSize={13}
title={button.title}
- type="accent"
+ type={button.type || 'grayBg'}
height={25}
/>
) : null}
diff --git a/apps/mobile/src/components/RestoreDialog/index.js b/apps/mobile/src/components/RestoreDialog/index.js
index 7a5d1beec..95be0f454 100644
--- a/apps/mobile/src/components/RestoreDialog/index.js
+++ b/apps/mobile/src/components/RestoreDialog/index.js
@@ -11,6 +11,7 @@ import {
} from '../../services/EventManager';
import {db} from '../../utils/database';
import {eCloseRestoreDialog, eOpenRestoreDialog} from '../../utils/Events';
+import {MMKV} from '../../utils/mmkv';
import {SIZE} from '../../utils/SizeUtils';
import storage from '../../utils/storage';
import {sleep, timeConverter} from '../../utils/TimeUtils';
@@ -19,6 +20,7 @@ import {Button} from '../Button';
import DialogHeader from '../Dialog/dialog-header';
import Seperator from '../Seperator';
import Paragraph from '../Typography/Paragraph';
+import * as ScopedStorage from 'react-native-scoped-storage';
const actionSheetRef = createRef();
let RNFetchBlob;
@@ -79,6 +81,7 @@ const RestoreDataComponent = ({close, setRestoring, restoring}) => {
const {colors} = state;
const [files, setFiles] = useState([]);
const [loading, setLoading] = useState(true);
+ const [backupDirectoryAndroid, setBackupDirectoryAndroid] = useState(false);
useEffect(() => {
checkBackups();
@@ -126,34 +129,112 @@ const RestoreDataComponent = ({close, setRestoring, restoring}) => {
};
const checkBackups = async () => {
- if (Platform.OS === 'android') {
- let granted = await storage.requestPermission();
- if (!granted) {
- ToastEvent.show({
- heading: 'Backup check failed',
- message:
- 'You must provide phone storage access to check for backups.',
- type: 'success',
- context: 'local'
- });
- return;
- }
- }
- RNFetchBlob = require('rn-fetch-blob').default;
try {
- let path = await storage.checkAndCreateDir('/backups/');
- let files = await RNFetchBlob.fs.lstat(path);
+ let files = [];
+ if (Platform.OS === 'android') {
+ let backupDirectory = await MMKV.getItem('backupStorageDir');
+ if (backupDirectory) {
+ backupDirectory = JSON.parse(backupDirectory);
+ setBackupDirectoryAndroid(backupDirectory);
+ files = await ScopedStorage.listFiles(backupDirectory.uri);
+ } else {
+ setLoading(false);
+ return;
+ }
+ } else {
+ RNFetchBlob = require('rn-fetch-blob').default;
+ let path = await storage.checkAndCreateDir('/backups/');
+ files = await RNFetchBlob.fs.lstat(path);
+ }
files = files.sort(function (a, b) {
timeA = a.lastModified;
timeB = b.lastModified;
return timeB - timeA;
});
-
setFiles(files);
setTimeout(() => {
setLoading(false);
}, 1000);
- } catch (e) {}
+ } catch (e) {
+ console.log(e);
+ setLoading(false);
+ }
+ };
+
+ const renderItem = ({item, index}) => (
+ <View
+ style={{
+ minHeight: 50,
+ justifyContent: 'space-between',
+ alignItems: 'center',
+ width: '100%',
+ borderRadius: 0,
+ flexDirection: 'row',
+ borderBottomWidth: 0.5,
+ borderBottomColor: colors.nav
+ }}>
+ <View
+ style={{
+ maxWidth: '75%'
+ }}>
+ <Paragraph size={SIZE.sm} style={{width: '100%', maxWidth: '100%'}}>
+ {timeConverter(item?.lastModified * 1)}
+ </Paragraph>
+ <Paragraph size={SIZE.xs}>
+ {(item.filename || item.name).replace('.nnbackup', '')}
+ </Paragraph>
+ </View>
+ <Button
+ title="Restore"
+ height={30}
+ type="accent"
+ style={{
+ borderRadius: 100,
+ paddingHorizontal: 12
+ }}
+ fontSize={SIZE.sm - 1}
+ onPress={() => restore(item, index)}
+ />
+ </View>
+ );
+
+ const button = {
+ title: 'Restore from files',
+ onPress: () => {
+ if (restoring) {
+ return;
+ }
+ DocumentPicker.pick()
+ .then(r => {
+ setRestoring(true);
+ fetch(r.uri).then(async r => {
+ try {
+ let backup = await r.json();
+ await db.backup.import(JSON.stringify(backup));
+ setRestoring(false);
+ initialize();
+
+ ToastEvent.show({
+ heading: 'Restore successful',
+ message: 'Your backup data has been restored successfully.',
+ type: 'success',
+ context: 'global'
+ });
+ actionSheetRef.current?.hide();
+ } catch (e) {
+ setRestoring(false);
+ ToastEvent.show({
+ heading: 'Restore failed',
+ message:
+ 'The selected backup data file is invalid. You must select a *.nnbackup file to restore.',
+ type: 'error',
+ context: 'local'
+ });
+ }
+ });
+ })
+ .catch(console.log);
+ }
};
return (
@@ -170,61 +251,20 @@ const RestoreDataComponent = ({close, setRestoring, restoring}) => {
}}>
<DialogHeader
title="Backups"
- paragraph="All the backups are stored in 'Phone Storage/Notesnook/Backups'."
- button={{
- title: 'Open File Manager',
- onPress: () => {
- if (restoring) {
- return;
- }
- DocumentPicker.pick()
- .then(r => {
- setRestoring(true);
- fetch(r.uri).then(async r => {
- try {
- let backup = await r.json();
-
- await db.backup.import(JSON.stringify(backup));
- setRestoring(false);
- initialize();
-
- ToastEvent.show({
- heading: 'Restore successful',
- message:
- 'Your backup data has been restored successfully.',
- type: 'success',
- context: 'global'
- });
- actionSheetRef.current?.hide();
- } catch (e) {
- setRestoring(false);
- ToastEvent.show({
- heading: 'Restore failed',
- message:
- 'The selected backup data file is invalid. You must select a *.nnbackup file to restore.',
- type: 'error',
- context: 'local'
- });
- }
- });
- })
- .catch(console.log);
- }
- }}
+ paragraph={`All the backups are stored in ${
+ Platform.OS === 'ios'
+ ? 'File Manager/Notesnook/Backups'
+ : 'selected backups folder.'
+ }`}
+ button={button}
/>
</View>
<Seperator half />
<FlatList
nestedScrollEnabled
- onScrollEndDrag={() => {
- actionSheetRef.current?.handleChildScrollEnd();
- }}
onMomentumScrollEnd={() => {
actionSheetRef.current?.handleChildScrollEnd();
}}
- onScrollAnimationEnd={() => {
- actionSheetRef.current?.handleChildScrollEnd();
- }}
ListEmptyComponent={
!restoring ? (
loading ? (
@@ -243,7 +283,56 @@ const RestoreDataComponent = ({close, setRestoring, restoring}) => {
alignItems: 'center',
height: 100
}}>
- <Paragraph color={colors.icon}>No backups found.</Paragraph>
+ {Platform.OS === 'android' && !backupDirectoryAndroid ? (
+ <>
+ <Button
+ title="Select backups folder"
+ icon="folder"
+ onPress={async () => {
+ let folder = await ScopedStorage.openDocumentTree(
+ true
+ );
+ let subfolder;
+ if (folder.name !== 'Notesnook backups') {
+ subfolder = await ScopedStorage.createDirectory(
+ folder.uri,
+ 'Notesnook backups'
+ );
+ } else {
+ subfolder = folder;
+ }
+ console.log(subfolder, folder);
+ MMKV.setItem(
+ 'backupStorageDir',
+ JSON.stringify(subfolder)
+ );
+ setBackupDirectoryAndroid(subfolder);
+ setLoading(true);
+ checkBackups();
+ }}
+ style={{
+ marginTop: 10,
+ paddingHorizontal: 12
+ }}
+ height={30}
+ width={null}
+ />
+
+ <Paragraph
+ style={{
+ textAlign: 'center',
+ marginTop: 5
+ }}
+ size={SIZE.xs}
+ textBreakStrategy="balanced"
+ color={colors.icon}>
+ Select the folder that includes your backup files to
+ list them here.
+ </Paragraph>
+ </>
+ ) : (
+ <Paragraph color={colors.icon}>No backups found</Paragraph>
+ )}
</View>
)
) : (
@@ -260,49 +349,17 @@ const RestoreDataComponent = ({close, setRestoring, restoring}) => {
</View>
)
}
- keyExtractor={item => item.filename}
+ keyExtractor={item => item.name || item.filename}
style={{
paddingHorizontal: 12
}}
data={restoring || loading ? [] : files}
- renderItem={({item, index}) => [
- <View
- style={{
- minHeight: 50,
- justifyContent: 'space-between',
- alignItems: 'center',
- width: '100%',
- borderRadius: 0,
- flexDirection: 'row',
- borderBottomWidth: 0.5,
- borderBottomColor: colors.nav
- }}>
- <View
- style={{
- maxWidth: '75%'
- }}>
- <Paragraph
- size={SIZE.sm}
- style={{width: '100%', maxWidth: '100%'}}>
- {timeConverter(item?.lastModified * 1)}
- </Paragraph>
- <Paragraph size={SIZE.xs}>
- {item.filename.replace('.nnbackup', '')}
- </Paragraph>
- </View>
- <Button
- title="Restore"
- width={80}
- height={30}
- onPress={() => restore(item, index)}
- />
- </View>
- ]}
+ renderItem={renderItem}
ListFooterComponent={
- restoring || loading ? null : (
+ restoring || loading || files.length === 0 ? null : (
<View
style={{
- height: 150
+ height: 50
}}
/>
)
diff --git a/apps/mobile/src/components/SortDialog/index.js b/apps/mobile/src/components/SortDialog/index.js
index ef1d7d77e..794176317 100644
--- a/apps/mobile/src/components/SortDialog/index.js
+++ b/apps/mobile/src/components/SortDialog/index.js
@@ -117,7 +117,8 @@ class SortDialog extends React.Component {
: 'sort-descending'
}
height={25}
- iconPosition="right"
+ iconPosition="left"
+ fontSize={SIZE.sm - 1}
type="grayBg"
style={{
borderRadius: 100
diff --git a/apps/mobile/src/services/Backup.js b/apps/mobile/src/services/Backup.js
index 76307a5da..1be8dbc8d 100644
--- a/apps/mobile/src/services/Backup.js
+++ b/apps/mobile/src/services/Backup.js
@@ -7,24 +7,45 @@ import {eCloseProgressDialog, eOpenProgressDialog} from '../utils/Events';
import Share from 'react-native-share';
import {Platform} from 'react-native';
import {sanitizeFilename} from '../utils/filename';
+import * as ScopedStorage from 'react-native-scoped-storage';
const MS_DAY = 86400000;
const MS_WEEK = MS_DAY * 7;
-let RNFetchBlob;
-async function run() {
+async function getDirectoryAndroid() {
+ let folder = await ScopedStorage.openDocumentTree(true);
+ if (!folder) return null;
+ let subfolder;
+ if (folder.name !== 'Notesnook backups') {
+ subfolder = await ScopedStorage.createDirectory(
+ folder.uri,
+ 'Notesnook backups'
+ );
+ } else {
+ subfolder = folder;
+ }
+ MMKV.setItem('backupStorageDir', JSON.stringify(subfolder));
+ return subfolder;
+}
+
+async function checkBackupDirExists() {
+ if (Platform.OS === 'ios') return true;
+ let dir;
if (Platform.OS === 'android') {
- let granted = await storage.requestPermission();
- if (!granted) {
- ToastEvent.show({
- heading: 'Cannot backup data',
- message: 'You must provide phone storage access to backup data.',
- type: 'error',
- context: 'local'
- });
- return;
+ dir = await MMKV.getItem('backupStorageDir');
+ if (dir) {
+ dir = JSON.parse(dir);
+ } else {
+ dir = await getDirectoryAndroid();
}
}
+ return dir;
+}
+
+let RNFetchBlob;
+async function run() {
+ let androidBackupDirectory = await checkBackupDirExists();
+ if (!androidBackupDirectory) return;
RNFetchBlob = require('rn-fetch-blob').default;
eSendEvent(eOpenProgressDialog, {
@@ -48,16 +69,35 @@ async function run() {
let backupName = 'notesnook_backup_' + Date.now();
backupName = sanitizeFilename(backupName, {replacement: '_'});
backupName = backupName + '.nnbackup';
- let path = await storage.checkAndCreateDir('/backups/');
- await RNFetchBlob.fs.writeFile(path + backupName, backup, 'utf8');
-
+ let path;
+ let backupFilePath;
+ if (Platform.OS === 'ios') {
+ path = await storage.checkAndCreateDir('/backups/');
+ await RNFetchBlob.fs.writeFile(path + backupName, backup, 'utf8');
+ backupFilePath = path + backupName;
+ } else {
+ backupFilePath = await ScopedStorage.writeFile(
+ androidBackupDirectory.uri,
+ backupName,
+ 'nnbackup/json',
+ backup,
+ 'utf8',
+ false
+ );
+ }
await MMKV.setItem('backupDate', JSON.stringify(Date.now()));
+ await MMKV.setItem(
+ 'askForBackup',
+ JSON.stringify({
+ timestamp: Date.now() + 86400000 * 3
+ })
+ );
ToastEvent.show({
heading: 'Backup successful',
message: 'Your backup is stored in Notesnook folder on your phone.',
type: 'success',
- context: 'local'
+ context: 'global'
});
eSendEvent(eOpenProgressDialog, {
@@ -66,33 +106,22 @@ async function run() {
paragraph:
'Share your backup to your cloud storage such as Dropbox or Google Drive so you do not lose it.',
noProgress: true,
- actionText: 'Share Backup File',
+ actionText: 'Share backup',
actionsArray: [
{
action: () => {
Share.open({
- url:
- Platform.OS === 'ios'
- ? path + backupName
- : 'file:/' + path + backupName,
- title: 'Save Backup to Cloud'
+ url: backupFilePath
}).catch(e => console.log);
},
- actionText: 'Share Backup File'
+ actionText: 'Share'
}
]
});
- console.log('updated ask for backup date');
- await MMKV.setItem(
- 'askForBackup',
- JSON.stringify({
- timestamp: Date.now() + 86400000 * 3
- })
- );
-
- return path + backupName;
+ console.log(backupFilePath);
+ return backupFilePath;
} catch (e) {
- console.log('backup error', e);
+ console.log('backup error: ', e);
eSendEvent(eCloseProgressDialog);
}
} else {
@@ -146,5 +175,7 @@ const checkAndRun = async () => {
export default {
checkBackupRequired,
run,
- checkAndRun
+ checkAndRun,
+ getDirectoryAndroid,
+ checkBackupDirExists
};
diff --git a/apps/mobile/src/views/Settings/index.js b/apps/mobile/src/views/Settings/index.js
index c0d54284f..9e7a2744c 100644
--- a/apps/mobile/src/views/Settings/index.js
+++ b/apps/mobile/src/views/Settings/index.js
@@ -1969,21 +1969,14 @@ export const SettingsBackupAndRestore = ({isSheet}) => {
} else {
await PremiumService.verify(async () => {
if (Platform.OS === 'android') {
- let granted = await Storage.requestPermission();
+ let granted = await Backup.checkBackupDirExists();
if (!granted) {
- ToastEvent.show({
- heading: 'Could not enable auto backups',
- message:
- 'You must give storage access to enable auto backups.',
- type: 'error',
- context: 'local'
- });
+ console.log('returning');
return;
}
}
await SettingsService.set('reminder', item.value);
- //await Backup.run();
- });
+ });
}
updateAskForBackup();
}}