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

WIP - fix: replace react-native-fs by expo-file-system and fix account backup #4239

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
12 changes: 6 additions & 6 deletions js/ios/Podfile.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion js/package.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { Icon } from '@ui-kitten/components'
import { readAsStringAsync, EncodingType } from 'expo-file-system'
import React, { useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { TouchableOpacity, View } from 'react-native'
import { readFile } from 'react-native-fs'

import { useAppDimensions } from '@berty/contexts/app-dimensions.context'
import { useStyles } from '@berty/contexts/styles'
Expand Down Expand Up @@ -106,7 +106,7 @@ export const PreviewComponent: React.FC<{
} else if (player?.isPaused) {
player?.playPause()
} else {
readFile(recordFilePath, 'base64')
readAsStringAsync(recordFilePath, { encoding: EncodingType.Base64 })
.then(response => {
console.log('SUCCESS')
setPlayer(playSoundFile(response))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import beapi from '@berty/api'
import { useMessengerClient, useThemeColor } from '@berty/hooks'
import { useNavigation } from '@berty/navigation'
import { checkPermissions } from '@berty/utils/react-native/checkPermissions'
import { getPath } from '@berty/utils/react-native/file-system'
import { copyToCache } from '@berty/utils/react-native/file-system'
import { PermissionType } from '@berty/utils/react-native/permissions'

import { GallerySection } from './GallerySection'
Expand Down Expand Up @@ -186,7 +186,7 @@ export const AddFileMenu: React.FC<{
})
let uri = res.uri
if (Platform.OS === 'android') {
uri = await getPath(uri)
uri = await copyToCache(uri)
}
prepareMediaAndSend([
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import CameraRoll from '@react-native-community/cameraroll'
import { Icon } from '@ui-kitten/components'
import { cacheDirectory, copyAsync, deleteAsync } from 'expo-file-system'
import React, { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import {
Expand All @@ -10,7 +11,6 @@ import {
Platform,
ActivityIndicator,
} from 'react-native'
import RNFS from 'react-native-fs'

import beapi from '@berty/api'
import { useStyles } from '@berty/contexts/styles'
Expand Down Expand Up @@ -79,10 +79,10 @@ export const GallerySection: React.FC<{
return item.uri
}
// Workaround to get uploadable uri from ios
const destination = `${RNFS.TemporaryDirectoryPath}${item.filename}`
const destination = `${cacheDirectory}${item.filename}`
try {
let absolutePath = item.uri && (await RNFS.copyAssetsFileIOS(item.uri, destination, 0, 0))
setTimeout(() => RNFS.unlink(destination), 10000)
let absolutePath = item.uri && (await copyAsync({ from: item.uri, to: destination }))
setTimeout(() => deleteAsync(destination), 10000)
return absolutePath
} catch (error) {
console.log(error)
Expand Down
27 changes: 15 additions & 12 deletions js/packages/components/debug/AppInspector.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { deleteAsync, getInfoAsync, readDirectoryAsync } from 'expo-file-system'
import React, { useCallback, useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import {
Expand All @@ -10,7 +11,6 @@ import {
StatusBar,
} from 'react-native'
import { NativeModules } from 'react-native'
import RNFS from 'react-native-fs'
import { SafeAreaView } from 'react-native-safe-area-context'

import beapi from '@berty/api'
Expand Down Expand Up @@ -102,28 +102,28 @@ class FSItem {
const fetchFSAccountList = (updateAccountFSFiles: (arg: Array<FSItem>) => void, t: any) => {
const f = async () => {
const rootDir = (await getRootDir()) + '/accounts'
const files = await RNFS.readDir(rootDir)
const files = await readDirectoryAsync(rootDir)
const items: Array<FSItem> = []

for (const file of files) {
const fsi = new FSItem()

try {
await RNFS.stat(rootDir + '/' + file.name + '/datastore.sqlite')
fsi.datastoreFound = true
const info = await getInfoAsync(rootDir + '/' + file + '/datastore.sqlite')
fsi.datastoreFound = info.exists
} catch (e) {}

try {
await RNFS.stat(rootDir + '/' + file.name + '/messenger.sqlite')
fsi.messengerDBFound = true
const info = await getInfoAsync(rootDir + '/' + file + '/messenger.sqlite')
fsi.messengerDBFound = info.exists
} catch (e) {}

try {
await RNFS.stat(rootDir + '/' + file.name + '/ipfs.sqlite')
fsi.ipfsRepoFound = true
const info = await getInfoAsync(rootDir + '/' + file + '/ipfs.sqlite')
fsi.ipfsRepoFound = info.exists
} catch (e) {}

fsi.fileName = file.name
fsi.fileName = file

items.push(fsi)
}
Expand Down Expand Up @@ -174,8 +174,11 @@ const accountAction = async (
let title = t('debug.inspector.accounts.action-delete.file-exists', { accountId: accountId })

try {
const stat = await RNFS.stat((await getRootDir()) + '/' + accountId)
if (stat.isFile()) {
const stat = await getInfoAsync((await getRootDir()) + '/' + accountId)
if (!stat.exists) {
throw new Error("file doesn't exist")
}
if (!stat.isDirectory) {
title = t('debug.inspector.accounts.action-delete.file-exists', { accountId: accountId })
} else {
title = t('debug.inspector.accounts.action-delete.account-exists', { accountId: accountId })
Expand Down Expand Up @@ -217,7 +220,7 @@ const accountAction = async (
onPress: confirmActionWrapper(
t('debug.inspector.accounts.action-delete.action-force-delete-confirm'),
async () => {
RNFS.unlink((await getRootDir()) + '/' + accountId)
deleteAsync((await getRootDir()) + '/' + accountId)
.then(() => Alert.alert(t('debug.inspector.accounts.action-delete.success-feedback')))
.catch((err: Error) => {
console.warn(err)
Expand Down
10 changes: 6 additions & 4 deletions js/packages/screens/chat/SharedMedias/SharedMedias.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import Clipboard from '@react-native-clipboard/clipboard'
import { Icon } from '@ui-kitten/components'
import { cacheDirectory, deleteAsync, EncodingType, writeAsStringAsync } from 'expo-file-system'
import LinkifyIt from 'linkify-it'
import React, { useState, useEffect } from 'react'
import {
Expand All @@ -13,7 +14,6 @@ import {
Share,
Platform,
} from 'react-native'
import RNFS from 'react-native-fs'
import Hyperlink from 'react-native-hyperlink'
import { TabView, SceneMap } from 'react-native-tab-view'
import { useSelector } from 'react-redux'
Expand Down Expand Up @@ -202,10 +202,12 @@ export const SharedMedias: ScreenFC<'Chat.SharedMedias'> = ({
return
}
const { data } = await retrieveMediaBytes(client, doc.cid)
const tmpFilename = RNFS.TemporaryDirectoryPath + '/' + (doc.filename || 'document')
const tmpFilename = cacheDirectory + (doc.filename || 'document')
try {
console.log('will share', data.length / 1000 / 1000, 'MB')
await RNFS.writeFile(tmpFilename, data.toString('base64'), 'base64')
await writeAsStringAsync(tmpFilename, data.toString('base64'), {
encoding: EncodingType.Base64,
})
const url = 'file://' + tmpFilename
if (Platform.OS === 'web') {
Clipboard.setString(url)
Expand All @@ -218,7 +220,7 @@ export const SharedMedias: ScreenFC<'Chat.SharedMedias'> = ({
}
}
try {
await RNFS.unlink(tmpFilename)
await deleteAsync(tmpFilename)
} catch (err) {
console.warn('failed to unlink shareable file: ', err)
}
Expand Down
1 change: 1 addition & 0 deletions js/packages/screens/settings/Accounts/Accounts.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ export const Accounts: ScreenFC<'Settings.Accounts'> = withInAppNotification(
<MenuItem
onPress={async () => {
try {
console.log('backing up', selectedAccount)
await exportAccountToFile(selectedAccount)
showNotification({
title: t('settings.accounts.backup-notif-title'),
Expand Down
57 changes: 13 additions & 44 deletions js/packages/screens/settings/ThemeEditor/ThemeEditor.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { Layout } from '@ui-kitten/components'
import { cacheDirectory, readAsStringAsync, writeAsStringAsync } from 'expo-file-system'
import { shareAsync } from 'expo-sharing'
import React from 'react'
import { useTranslation } from 'react-i18next'
import { Platform, ScrollView, StatusBar, View } from 'react-native'
import DocumentPicker from 'react-native-document-picker'
import RNFS from 'react-native-fs'
import { withInAppNotification } from 'react-native-in-app-notification'
import Share from 'react-native-share'
import { useDispatch, useSelector } from 'react-redux'

import { TextualDropdown } from '@berty/components'
Expand All @@ -22,14 +22,13 @@ import {
selectThemeSelected,
setTheme,
} from '@berty/redux/reducers/theme.reducer'
import { createAndSaveFile, getPath } from '@berty/utils/react-native/file-system'

import { ThemeColorName } from './components/ThemeColorName'

const openThemeColorFile = async () => {
try {
return await DocumentPicker.pickSingle({
type: DocumentPicker.types.allFiles,
type: Platform.OS === 'android' ? 'application/json' : 'public.json',
})
} catch (err: any) {
if (DocumentPicker.isCancel(err)) {
Expand All @@ -40,29 +39,16 @@ const openThemeColorFile = async () => {
}
}

const importColorThemeFileFromStorage = async (uri: string): Promise<string> => {
const file = Platform.OS === 'android' ? await getPath(uri) : uri
const theme = await RNFS.readFile(file.replace(/^file:\/\//, ''), 'utf8')
return theme
}

const shareColorTheme = async (fileName: string) => {
const outFile = RNFS.TemporaryDirectoryPath + `/${fileName}` + '.json'
await Share.open({
title: 'Berty theme',
url: `file://${outFile}`,
type: '*/*',
const shareColorTheme = async (themeJSON: string, themeName: string): Promise<void> => {
const outFile = `${cacheDirectory}${themeName}.json`
await writeAsStringAsync(outFile, themeJSON)
await shareAsync(outFile, {
UTI: 'public.json',
dialogTitle: `Berty ${themeName} theme`,
mimeType: 'application/json',
})
}

const exportColorThemeToFile = async (themeColor: any, fileName: string): Promise<void> => {
const outFile = RNFS.TemporaryDirectoryPath + `/${fileName}` + '.json'
await RNFS.writeFile(outFile, themeColor, 'utf8')
Platform.OS === 'android'
? await createAndSaveFile(outFile, fileName, 'json')
: await shareColorTheme(fileName)
}

const BodyFileThemeEditor: React.FC<{}> = withInAppNotification(({ showNotification }: any) => {
const colors = useThemeColor()
const { t } = useTranslation()
Expand All @@ -79,7 +65,7 @@ const BodyFileThemeEditor: React.FC<{}> = withInAppNotification(({ showNotificat
if (!document) {
return
}
const themeColors = JSON.parse(await importColorThemeFileFromStorage(document.uri))
const themeColors = JSON.parse(await readAsStringAsync(document.uri))
const themeName = document.name.split('.')[0]
dispatch(importTheme({ themeName, colors: themeColors }))
} catch (err) {
Expand All @@ -96,28 +82,11 @@ const BodyFileThemeEditor: React.FC<{}> = withInAppNotification(({ showNotificat
<FloatingMenuItemWithIcon
iconName='color-palette-outline'
onPress={async () => {
await exportColorThemeToFile(JSON.stringify(colors), selectedTheme)
if (Platform.OS === 'android') {
showNotification({
title: t('settings.theme-editor.notification-file-saved.title'),
message: t('settings.theme-editor.notification-file-saved.desc'),
additionalProps: { type: 'message' },
})
}
await shareColorTheme(JSON.stringify(colors), selectedTheme)
}}
>
{Platform.OS === 'android'
? t('settings.theme-editor.export')
: t('settings.theme-editor.share')}
{t('settings.theme-editor.share')}
</FloatingMenuItemWithIcon>
{Platform.OS === 'android' && (
<FloatingMenuItemWithIcon
iconName='color-palette-outline'
onPress={async () => shareColorTheme(selectedTheme)}
>
{t('settings.theme-editor.share')}
</FloatingMenuItemWithIcon>
)}
<FloatingMenuItemWithIcon
iconName='color-palette-outline'
onPress={() => dispatch(deleteAddedThemes())}
Expand Down