Android: Fixes #5779: Fixed android filesystem sync (#6395)

pull/6658/head
jd1378 2022-07-10 15:26:24 +01:00 committed by GitHub
parent 55d98346ee
commit effba83a0e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
46 changed files with 2715 additions and 27 deletions

View File

@ -1933,6 +1933,9 @@ packages/plugins/ToggleSidebars/api/types.js.map
packages/plugins/ToggleSidebars/src/index.d.ts
packages/plugins/ToggleSidebars/src/index.js
packages/plugins/ToggleSidebars/src/index.js.map
packages/react-native-saf-x/src/index.d.ts
packages/react-native-saf-x/src/index.js
packages/react-native-saf-x/src/index.js.map
packages/renderer/HtmlToHtml.d.ts
packages/renderer/HtmlToHtml.js
packages/renderer/HtmlToHtml.js.map

3
.gitignore vendored
View File

@ -1923,6 +1923,9 @@ packages/plugins/ToggleSidebars/api/types.js.map
packages/plugins/ToggleSidebars/src/index.d.ts
packages/plugins/ToggleSidebars/src/index.js
packages/plugins/ToggleSidebars/src/index.js.map
packages/react-native-saf-x/src/index.d.ts
packages/react-native-saf-x/src/index.js
packages/react-native-saf-x/src/index.js.map
packages/renderer/HtmlToHtml.d.ts
packages/renderer/HtmlToHtml.js
packages/renderer/HtmlToHtml.js.map

View File

@ -26,7 +26,7 @@ const sharp = require('sharp');
const { shimInit } = require('@joplin/lib/shim-init-node.js');
const shim = require('@joplin/lib/shim').default;
const { _ } = require('@joplin/lib/locale');
const { FileApiDriverLocal } = require('@joplin/lib/file-api-driver-local.js');
const { FileApiDriverLocal } = require('@joplin/lib/file-api-driver-local');
const EncryptionService = require('@joplin/lib/services/e2ee/EncryptionService').default;
const envFromArgs = require('@joplin/lib/envFromArgs');
const nodeSqlite = require('sqlite3');

View File

@ -26,7 +26,7 @@ const shim = require('@joplin/lib/shim').default;
const { shimInit } = require('@joplin/lib/shim-init-node.js');
const bridge = require('@electron/remote').require('./bridge').default;
const EncryptionService = require('@joplin/lib/services/e2ee/EncryptionService').default;
const { FileApiDriverLocal } = require('@joplin/lib/file-api-driver-local.js');
const { FileApiDriverLocal } = require('@joplin/lib/file-api-driver-local');
const React = require('react');
const nodeSqlite = require('sqlite3');

View File

@ -65,3 +65,5 @@ lib/rnInjectedJs/
dist/
components/NoteEditor/CodeMirror.bundle.js
components/NoteEditor/CodeMirror.bundle.min.js
utils/fs-driver-android.js

View File

@ -1,6 +1,7 @@
/* eslint-disable @typescript-eslint/explicit-member-accessibility */
import Slider from '@react-native-community/slider';
const React = require('react');
const { Platform, Linking, View, Switch, StyleSheet, ScrollView, Text, Button, TouchableOpacity, TextInput, Alert, PermissionsAndroid } = require('react-native');
const { Platform, Linking, View, Switch, StyleSheet, ScrollView, Text, Button, TouchableOpacity, TextInput, Alert, PermissionsAndroid, TouchableNativeFeedback } = require('react-native');
import Setting, { AppType } from '@joplin/lib/models/Setting';
import NavService from '@joplin/lib/services/NavService';
import ReportService from '@joplin/lib/services/ReportService';
@ -20,6 +21,7 @@ const { Dropdown } = require('../Dropdown.js');
const { themeStyle } = require('../global-style.js');
const shared = require('@joplin/lib/components/shared/config-shared.js');
import SyncTargetRegistry from '@joplin/lib/SyncTargetRegistry';
import { openDocumentTree } from '@joplin/react-native-saf-x';
const RNFS = require('react-native-fs');
class ConfigScreenComponent extends BaseScreenComponent {
@ -37,12 +39,27 @@ class ConfigScreenComponent extends BaseScreenComponent {
creatingReport: false,
profileExportStatus: 'idle',
profileExportPath: '',
fileSystemSyncPath: Setting.value('sync.2.path'),
};
this.scrollViewRef_ = React.createRef();
shared.init(this, reg);
this.selectDirectoryButtonPress = async () => {
try {
const doc = await openDocumentTree(true);
if (doc?.uri) {
this.setState({ fileSystemSyncPath: doc.uri });
shared.updateSettingValue(this, 'sync.2.path', doc.uri);
} else {
throw new Error('User cancelled operation');
}
} catch (e) {
reg.logger().info('Didn\'t pick sync dir: ', e);
}
};
this.checkSyncConfig_ = async () => {
// to ignore TLS erros we need to chage the global state of the app, if the check fails we need to restore the original state
// this call sets the new value and returns the previous one which we can use later to revert the change
@ -58,8 +75,15 @@ class ConfigScreenComponent extends BaseScreenComponent {
};
this.saveButton_press = async () => {
if (this.state.changedSettingKeys.includes('sync.target') && this.state.settings['sync.target'] === SyncTargetRegistry.nameToId('filesystem') && !(await this.checkFilesystemPermission())) {
Alert.alert(_('Warning'), _('In order to use file system synchronisation your permission to write to external storage is required.'));
if (this.state.changedSettingKeys.includes('sync.target') && this.state.settings['sync.target'] === SyncTargetRegistry.nameToId('filesystem')) {
if (Platform.OS === 'android') {
if (Platform.Version < 29) {
if (!(await this.checkFilesystemPermission())) {
Alert.alert(_('Warning'), _('In order to use file system synchronisation your permission to write to external storage is required.'));
}
}
}
// Save settings anyway, even if permission has not been granted
}
@ -476,6 +500,20 @@ class ConfigScreenComponent extends BaseScreenComponent {
</View>
);
} else if (md.type == Setting.TYPE_STRING) {
if (md.key === 'sync.2.path' && Platform.OS === 'android' && Platform.Version > 28) {
return (
<TouchableNativeFeedback key={key} onPress={this.selectDirectoryButtonPress} style={this.styles().settingContainer}>
<View style={this.styles().settingContainer}>
<Text key="label" style={this.styles().settingText}>
{md.label()}
</Text>
<Text style={this.styles().settingControl}>
{this.state.fileSystemSyncPath}
</Text>
</View>
</TouchableNativeFeedback>
);
}
return (
<View key={key} style={this.styles().settingContainer}>
<Text key="label" style={this.styles().settingText}>

View File

@ -44,6 +44,7 @@ module.exports = {
'@joplin/tools': path.resolve(__dirname, '../tools/'),
'@joplin/fork-htmlparser2': path.resolve(__dirname, '../fork-htmlparser2/'),
'@joplin/fork-uslug': path.resolve(__dirname, '../fork-uslug/'),
'@joplin/react-native-saf-x': path.resolve(__dirname, '../react-native-saf-x/'),
},
{
get: (target, name) => {
@ -62,5 +63,6 @@ module.exports = {
path.resolve(__dirname, '../tools'),
path.resolve(__dirname, '../fork-htmlparser2'),
path.resolve(__dirname, '../fork-uslug'),
path.resolve(__dirname, '../react-native-saf-x'),
],
};

View File

@ -6,6 +6,7 @@
"private": true,
"scripts": {
"start": "react-native start --reset-cache",
"android": "react-native run-android",
"build": "gulp build",
"tsc": "tsc --project tsconfig.json",
"watch": "tsc --watch --preserveWatchOutput --project tsconfig.json",
@ -16,6 +17,7 @@
},
"dependencies": {
"@joplin/lib": "~2.8",
"@joplin/react-native-saf-x": "~0.5",
"@joplin/renderer": "~2.8",
"@react-native-community/clipboard": "^1.5.0",
"@react-native-community/datetimepicker": "^3.0.3",

View File

@ -70,7 +70,7 @@ const { SideMenuContentNote } = require('./components/side-menu-content-note.js'
const { DatabaseDriverReactNative } = require('./utils/database-driver-react-native');
import { reg } from '@joplin/lib/registry';
const { defaultState } = require('@joplin/lib/reducer');
const { FileApiDriverLocal } = require('@joplin/lib/file-api-driver-local.js');
const { FileApiDriverLocal } = require('@joplin/lib/file-api-driver-local');
import ResourceFetcher from '@joplin/lib/services/ResourceFetcher';
import SearchEngine from '@joplin/lib/services/searchengine/SearchEngine';
const WelcomeUtils = require('@joplin/lib/WelcomeUtils');

View File

@ -1,6 +1,13 @@
import FsDriverBase from '@joplin/lib/fs-driver-base';
import FsDriverBase, { ReadDirStatsOptions } from '@joplin/lib/fs-driver-base';
const RNFetchBlob = require('rn-fetch-blob').default;
const RNFS = require('react-native-fs');
import RNSAF, { Encoding, DocumentFileDetail } from '@joplin/react-native-saf-x';
const ANDROID_URI_PREFIX = 'content://';
function isScopedUri(path: string) {
return path.includes(ANDROID_URI_PREFIX);
}
export default class FsDriverRN extends FsDriverBase {
public appendFileSync() {
@ -9,11 +16,17 @@ export default class FsDriverRN extends FsDriverBase {
// Encoding can be either "utf8" or "base64"
public appendFile(path: string, content: any, encoding = 'base64') {
if (isScopedUri(path)) {
return RNSAF.writeFile(path, content, { encoding: encoding as Encoding, append: true });
}
return RNFS.appendFile(path, content, encoding);
}
// Encoding can be either "utf8" or "base64"
public writeFile(path: string, content: any, encoding = 'base64') {
if (isScopedUri(path)) {
return RNSAF.writeFile(path, content, { encoding: encoding as Encoding });
}
// We need to use rn-fetch-blob here due to this bug:
// https://github.com/itinance/react-native-fs/issues/700
return RNFetchBlob.fs.writeFile(path, content, encoding);
@ -26,52 +39,105 @@ export default class FsDriverRN extends FsDriverBase {
// Returns a format compatible with Node.js format
private rnfsStatToStd_(stat: any, path: string) {
let birthtime;
const mtime = stat.lastModified ? new Date(stat.lastModified) : stat.mtime;
if (stat.lastModified) {
birthtime = new Date(stat.lastModified);
} else if (stat.ctime) {
// Confusingly, "ctime" normally means "change time" but here it's used as "creation time". Also sometimes it is null
birthtime = stat.ctime;
} else {
birthtime = stat.mtime;
}
return {
birthtime: stat.ctime ? stat.ctime : stat.mtime, // Confusingly, "ctime" normally means "change time" but here it's used as "creation time". Also sometimes it is null
mtime: stat.mtime,
isDirectory: () => stat.isDirectory(),
birthtime,
mtime,
isDirectory: () => stat.type ? stat.type === 'directory' : stat.isDirectory(),
path: path,
size: stat.size,
};
}
public async isDirectory(path: string): Promise<boolean> {
return (await this.stat(path)).isDirectory();
}
public async readDirStats(path: string, options: any = null) {
if (!options) options = {};
if (!('recursive' in options)) options.recursive = false;
let items = [];
const isScoped = isScopedUri(path);
let stats = [];
try {
items = await RNFS.readDir(path);
if (isScoped) {
stats = await RNSAF.listFiles(path);
} else {
stats = await RNFS.readDir(path);
}
} catch (error) {
throw new Error(`Could not read directory: ${path}: ${error.message}`);
}
let output: any[] = [];
for (let i = 0; i < items.length; i++) {
const item = items[i];
const relativePath = item.path.substr(path.length + 1);
output.push(this.rnfsStatToStd_(item, relativePath));
for (let i = 0; i < stats.length; i++) {
const stat = stats[i];
const relativePath = (isScoped ? stat.uri : stat.path).substr(path.length + 1);
output.push(this.rnfsStatToStd_(stat, relativePath));
output = await this.readDirStatsHandleRecursion_(path, item, output, options);
if (isScoped) {
output = await this.readUriDirStatsHandleRecursion_(stat, output, options);
} else {
output = await this.readDirStatsHandleRecursion_(path, stat, output, options);
}
}
return output;
}
protected async readUriDirStatsHandleRecursion_(stat: DocumentFileDetail, output: DocumentFileDetail[], options: ReadDirStatsOptions) {
if (options.recursive && stat.type === 'directory') {
const subStats = await this.readDirStats(stat.uri, options);
for (let j = 0; j < subStats.length; j++) {
const subStat = subStats[j];
output.push(subStat);
}
}
return output;
}
public async move(source: string, dest: string) {
if (isScopedUri(source) && isScopedUri(dest)) {
await RNSAF.moveFile(source, dest, { replaceIfDestinationExists: true });
} else if (isScopedUri(source) || isScopedUri(dest)) {
throw new Error('Move between different storage types not supported');
}
return RNFS.moveFile(source, dest);
}
public async exists(path: string) {
if (isScopedUri(path)) {
return RNSAF.exists(path);
}
return RNFS.exists(path);
}
public async mkdir(path: string) {
if (isScopedUri(path)) {
await RNSAF.mkdir(path);
return;
}
return RNFS.mkdir(path);
}
public async stat(path: string) {
try {
const r = await RNFS.stat(path);
let r;
if (isScopedUri(path)) {
r = await RNSAF.stat(path);
} else {
r = await RNFS.stat(path);
}
return this.rnfsStatToStd_(r, path);
} catch (error) {
if (error && ((error.message && error.message.indexOf('exist') >= 0) || error.code === 'ENOENT')) {
@ -93,6 +159,9 @@ export default class FsDriverRN extends FsDriverBase {
}
public async open(path: string, mode: number) {
if (isScopedUri(path)) {
throw new Error('open() not implemented in FsDriverAndroid');
}
// Note: RNFS.read() doesn't provide any way to know if the end of file has been reached.
// So instead we stat the file here and use stat.size to manually check for end of file.
// Bug: https://github.com/itinance/react-native-fs/issues/342
@ -112,6 +181,9 @@ export default class FsDriverRN extends FsDriverBase {
public readFile(path: string, encoding = 'utf8') {
if (encoding === 'Buffer') throw new Error('Raw buffer output not supported for FsDriverRN.readFile');
if (isScopedUri(path)) {
return RNSAF.readFile(path, { encoding: encoding as Encoding });
}
return RNFS.readFile(path, encoding);
}
@ -119,6 +191,12 @@ export default class FsDriverRN extends FsDriverBase {
public async copy(source: string, dest: string) {
let retry = false;
try {
if (isScopedUri(source) && isScopedUri(dest)) {
await RNSAF.copyFile(source, dest, { replaceIfDestinationExists: true });
return;
} else if (isScopedUri(source) || isScopedUri(dest)) {
throw new Error('Move between different storage types not supported');
}
await RNFS.copyFile(source, dest);
} catch (error) {
// On iOS it will throw an error if the file already exist
@ -131,6 +209,10 @@ export default class FsDriverRN extends FsDriverBase {
public async unlink(path: string) {
try {
if (isScopedUri(path)) {
await RNSAF.unlink(path);
return;
}
await RNFS.unlink(path);
} catch (error) {
if (error && ((error.message && error.message.indexOf('exist') >= 0) || error.code === 'ENOENT')) {

View File

@ -22,7 +22,9 @@ function shimInit() {
shim.sjclModule = require('@joplin/lib/vendor/sjcl-rn.js');
shim.fsDriver = () => {
if (!shim.fsDriver_) shim.fsDriver_ = new FsDriverRN();
if (!shim.fsDriver_) {
shim.fsDriver_ = new FsDriverRN();
}
return shim.fsDriver_;
};

View File

@ -1,2 +1,2 @@
plugin_types/
markdownUtils.test.js
markdownUtils.test.js

View File

@ -2,7 +2,7 @@ const BaseSyncTarget = require('./BaseSyncTarget').default;
const { _ } = require('./locale');
const Setting = require('./models/Setting').default;
const { FileApi } = require('./file-api.js');
const { FileApiDriverLocal } = require('./file-api-driver-local.js');
const { FileApiDriverLocal } = require('./file-api-driver-local');
const Synchronizer = require('./Synchronizer').default;
class SyncTargetFilesystem extends BaseSyncTarget {

View File

@ -23,7 +23,7 @@ class FileApiDriverLocal {
}
fsDriver() {
if (!FileApiDriverLocal.fsDriver_) throw new Error('FileApiDriverLocal.fsDriver_ not set!');
if (!FileApiDriverLocal.fsDriver_) { throw new Error('FileApiDriverLocal.fsDriver_ not set!'); }
return FileApiDriverLocal.fsDriver_;
}
@ -93,6 +93,7 @@ class FileApiDriverLocal {
}
async get(path, options) {
if (!options) options = {};
let output = null;
try {
@ -151,7 +152,6 @@ class FileApiDriverLocal {
} catch (error) {
throw this.fsErrorToJsError_(error, path);
}
// if (!options) options = {};
// if (options.source === 'file') content = await fs.readFile(options.path);
@ -223,8 +223,15 @@ class FileApiDriverLocal {
}
async clearRoot(baseDir) {
await this.fsDriver().remove(baseDir);
await this.fsDriver().mkdir(baseDir);
if (baseDir.startsWith('content://')) {
const result = await this.list(baseDir);
for (const item of result.items) {
await this.fsDriver().remove(item.path);
}
} else {
await this.fsDriver().remove(baseDir);
await this.fsDriver().mkdir(baseDir);
}
}
}

View File

@ -3,7 +3,7 @@
const fs = require('fs-extra');
const shim = require('./shim').default;
const GeolocationNode = require('./geolocation-node').default;
const { FileApiDriverLocal } = require('./file-api-driver-local.js');
const { FileApiDriverLocal } = require('./file-api-driver-local');
const { setLocale, defaultLocale, closestSupportedLocale } = require('./locale');
const FsDriverNode = require('./fs-driver-node').default;
const mimeUtils = require('./mime-utils.js').mime;

View File

@ -30,7 +30,7 @@ import MasterKey from '../models/MasterKey';
import BaseItem from '../models/BaseItem';
import { FileApi } from '../file-api';
const FileApiDriverMemory = require('../file-api-driver-memory').default;
const { FileApiDriverLocal } = require('../file-api-driver-local.js');
const { FileApiDriverLocal } = require('../file-api-driver-local');
const { FileApiDriverWebDav } = require('../file-api-driver-webdav.js');
const { FileApiDriverDropbox } = require('../file-api-driver-dropbox.js');
const { FileApiDriverOneDrive } = require('../file-api-driver-onedrive.js');

View File

@ -0,0 +1,15 @@
# EditorConfig helps developers define and maintain consistent
# coding styles between different editors and IDEs
# editorconfig.org
root = true
[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

View File

@ -0,0 +1,3 @@
node_modules/
lib/
.env

View File

@ -0,0 +1,3 @@
*.pbxproj -text
# specific for windows script files
*.bat text eol=crlf

66
packages/react-native-saf-x/.gitignore vendored Normal file
View File

@ -0,0 +1,66 @@
# OSX
#
.DS_Store
# XDE
.expo/
# VSCode
.vscode/
jsconfig.json
# Xcode
#
build/
*.pbxuser
!default.pbxuser
*.mode1v3
!default.mode1v3
*.mode2v3
!default.mode2v3
*.perspectivev3
!default.perspectivev3
xcuserdata
*.xccheckout
*.moved-aside
DerivedData
*.hmap
*.ipa
*.xcuserstate
project.xcworkspace
# Android/IJ
#
.classpath
.cxx
.gradle
.idea
.project
.settings
local.properties
android.iml
# Cocoapods
#
example/ios/Pods
# node.js
#
node_modules/
npm-debug.log
yarn-debug.log
yarn-error.log
# BUCK
buck-out/
\.buckd/
android/app/libs
android/keystores/debug.keystore
# Expo
.expo/*
# generated by bob
lib/
.env
docs

View File

@ -0,0 +1,3 @@
# Override Yarn command so we can automatically setup the repo on running `yarn`
yarn-path "scripts/bootstrap.js"

View File

@ -0,0 +1,196 @@
# Contributing
We want this community to be friendly and respectful to each other. Please follow it in all your interactions with the project.
## Development workflow
To get started with the project, run `yarn` in the root directory to install the required dependencies for each package:
```sh
yarn
```
> While it's possible to use [`npm`](https://github.com/npm/cli), the tooling is built around [`yarn`](https://classic.yarnpkg.com/), so you'll have an easier time if you use `yarn` for development.
While developing, you can run the [example app](/example/) to test your changes. Any changes you make in your library's JavaScript code will be reflected in the example app without a rebuild. If you change any native code, then you'll need to rebuild the example app.
To start the packager:
```sh
yarn example start
```
To run the example app on Android:
```sh
yarn example android
```
To run the example app on iOS:
```sh
yarn example ios
```
Make sure your code passes TypeScript and ESLint. Run the following to verify:
```sh
yarn typescript
yarn lint
```
To fix formatting errors, run the following:
```sh
yarn lint --fix
```
Remember to add tests for your change if possible. Run the unit tests by:
```sh
yarn test
```
To edit the Objective-C files, open `example/ios/SafXExample.xcworkspace` in XCode and find the source files at `Pods > Development Pods > react-native-saf-x`.
To edit the Kotlin files, open `example/android` in Android studio and find the source files at `reactnativesafx` under `Android`.
### Commit message convention
We follow the [conventional commits specification](https://www.conventionalcommits.org/en) for our commit messages:
- `fix`: bug fixes, e.g. fix crash due to deprecated method.
- `feat`: new features, e.g. add new method to the module.
- `refactor`: code refactor, e.g. migrate from class components to hooks.
- `docs`: changes into documentation, e.g. add usage example for the module..
- `test`: adding or updating tests, e.g. add integration tests using detox.
- `chore`: tooling changes, e.g. change CI config.
Our pre-commit hooks verify that your commit message matches this format when committing.
### Linting and tests
[ESLint](https://eslint.org/), [Prettier](https://prettier.io/), [TypeScript](https://www.typescriptlang.org/)
We use [TypeScript](https://www.typescriptlang.org/) for type checking, [ESLint](https://eslint.org/) with [Prettier](https://prettier.io/) for linting and formatting the code, and [Jest](https://jestjs.io/) for testing.
Our pre-commit hooks verify that the linter and tests pass when committing.
### Publishing to npm
We use [release-it](https://github.com/release-it/release-it) to make it easier to publish new versions. It handles common tasks like bumping version based on semver, creating tags and releases etc.
To publish new versions, run the following:
```sh
yarn release
```
### Scripts
The `package.json` file contains various scripts for common tasks:
- `yarn bootstrap`: setup project by installing all dependencies and pods.
- `yarn typescript`: type-check files with TypeScript.
- `yarn lint`: lint files with ESLint.
- `yarn test`: run unit tests with Jest.
- `yarn example start`: start the Metro server for the example app.
- `yarn example android`: run the example app on Android.
- `yarn example ios`: run the example app on iOS.
### Sending a pull request
> **Working on your first pull request?** You can learn how from this _free_ series: [How to Contribute to an Open Source Project on GitHub](https://app.egghead.io/playlists/how-to-contribute-to-an-open-source-project-on-github).
When you're sending a pull request:
- Prefer small pull requests focused on one change.
- Verify that linters and tests are passing.
- Review the documentation to make sure it looks good.
- Follow the pull request template when opening a pull request.
- For pull requests that change the API or implementation, discuss with maintainers first by opening an issue.
## Code of Conduct
### Our Pledge
We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
### Our Standards
Examples of behavior that contributes to a positive environment for our community include:
- Demonstrating empathy and kindness toward other people
- Being respectful of differing opinions, viewpoints, and experiences
- Giving and gracefully accepting constructive feedback
- Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
- Focusing on what is best not just for us as individuals, but for the overall community
Examples of unacceptable behavior include:
- The use of sexualized language or imagery, and sexual attention or
advances of any kind
- Trolling, insulting or derogatory comments, and personal or political attacks
- Public or private harassment
- Publishing others' private information, such as a physical or email
address, without their explicit permission
- Other conduct which could reasonably be considered inappropriate in a
professional setting
### Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
### Scope
This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
### Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at [INSERT CONTACT METHOD]. All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the reporter of any incident.
### Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
#### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
#### 2. Warning
**Community Impact**: A violation through a single incident or series of actions.
**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
#### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
#### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within the community.
### Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see the FAQ at
https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.

View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2021 Javad Mnjd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -0,0 +1,563 @@
# react-native-saf-x
<a href="https://www.npmjs.com/package/react-native-saf-x" target="_blank">
<img src="https://img.shields.io/npm/v/react-native-saf-x?color=green"/>
</a>
A module to help simplify usage of scoped storages on android.
intended to use when targeting Android API level 30+
## Installation
```sh
npm install react-native-saf-x
```
or
```sh
yarn add react-native-saf-x
```
## Usage
After receiving a content uri using `openDocumentTree` function,
you can use this as if like it's a normal path like we are used to.
This is the intended behaviour,
if you find any problems or if something does not behave as intended,
please create an issue.
Note that each method can reject when there's an unexpected error or when the permission is revoked.
Example:
```js
import { openDocumentTree, mkdir } from "react-native-saf-x";
// somewhere in the app .....
async function testIt() {
const doc = await openDocumentTree(true);
if (doc && doc.uri) {
// user has selected a directory and uri is available
// you can save this uri as base directory in your app and reuse it anywhere you want
await mkdir(doc.uri + '/foo/bar'); // creates foo/bar folder and subfolder at selected directory
}
}
```
For more examples look at example folder in the source.
## Table of contents
- [Installation](#installation)
- [Usage](#usage)
- [Type aliases](#type-aliases)
- [Functions](#functions)
- [Caveats](#caveats)
- [Thanks to](#thanks-to)
- [Contributing](#contributing)
- [License](#license)
### Type aliases
- [CreateDocumentOptions](#createdocumentoptions)
- [DocumentFileDetail](#documentfiledetail)
- [Encoding](#encoding)
- [FileOperationOptions](#fileoperationoptions)
### Functions
- [copyFile](#copyfile)
- [createDocument](#createdocument)
- [createFile](#createfile)
- [exists](#exists)
- [getPersistedUriPermissions](#getpersisteduripermissions)
- [hasPermission](#haspermission)
- [listFiles](#listfiles)
- [mkdir](#mkdir)
- [moveFile](#movefile)
- [openDocument](#opendocument)
- [openDocumentTree](#opendocumenttree)
- [readFile](#readfile)
- [releasePersistableUriPermission](#releasepersistableuripermission)
- [rename](#rename)
- [stat](#stat)
- [unlink](#unlink)
- [writeFile](#writefile)
## Type aliases
### CreateDocumentOptions
Ƭ **CreateDocumentOptions**: [`FileOperationOptions`](#fileoperationoptions) & { `initialName?`: `string` }
#### Defined in
[index.tsx:80](https://github.com/jd1378/react-native-saf-x/blob/e0f8106/src/index.tsx#L80)
___
### DocumentFileDetail
Ƭ **DocumentFileDetail**: `Object`
#### Type declaration
| Name | Type |
| :------ | :------ |
| `lastModified` | `number` |
| `mime?` | `string` |
| `name` | `string` |
| `size?` | `number` |
| `type` | ``"directory"`` \| ``"file"`` |
| `uri` | `string` |
#### Defined in
[index.tsx:60](https://github.com/jd1378/react-native-saf-x/blob/e0f8106/src/index.tsx#L60)
___
### Encoding
Ƭ **Encoding**: ``"utf8"`` \| ``"base64"`` \| ``"ascii"``
#### Defined in
[index.tsx:22](https://github.com/jd1378/react-native-saf-x/blob/e0f8106/src/index.tsx#L22)
___
### FileOperationOptions
Ƭ **FileOperationOptions**: `Object`
#### Type declaration
| Name | Type | Description |
| :------ | :------ | :------ |
| `append?` | `boolean` | Append data to the file. If not set file content will be overwritten. |
| `encoding?` | [`Encoding`](#encoding) | Defaults to `'utf8'` |
| `mimeType?` | `string` | mime type of the file being saved. Defaults to '\*\/\*' |
#### Defined in
[index.tsx:69](https://github.com/jd1378/react-native-saf-x/blob/e0f8106/src/index.tsx#L69)
## Functions
### copyFile
**copyFile**(`srcUri`, `destUri`, `options?`): `Promise`<``null`` \| [`DocumentFileDetail`](#documentfiledetail)\>
Copy file from source uri to destination uri.
promise Rejects if destination already exists and `replaceIfDestinationExists` option is not set to true.
Does not support moving directories.
#### Parameters
| Name | Type |
| :------ | :------ |
| `srcUri` | `string` |
| `destUri` | `string` |
| `options?` | `FileTransferOptions` |
#### Returns
`Promise`<``null`` \| [`DocumentFileDetail`](#documentfiledetail)\>
#### Defined in
[index.tsx:214](https://github.com/jd1378/react-native-saf-x/blob/e0f8106/src/index.tsx#L214)
___
### createDocument
**createDocument**(`data`, `options?`): `Promise`<``null`` \| [`DocumentFileDetail`](#documentfiledetail)\>
Open the Document Picker to save a file.
Returns an object of type `DocumentFileDetail` or `null` if user did not select a file.
#### Parameters
| Name | Type |
| :------ | :------ |
| `data` | `string` |
| `options?` | [`CreateDocumentOptions`](#createdocumentoptions) |
#### Returns
`Promise`<``null`` \| [`DocumentFileDetail`](#documentfiledetail)\>
#### Defined in
[index.tsx:105](https://github.com/jd1378/react-native-saf-x/blob/e0f8106/src/index.tsx#L105)
___
### createFile
**createFile**(`uriString`, `options?`): `Promise`<[`DocumentFileDetail`](#documentfiledetail)\>
Creates an empty file at given uri.
Rejects if a file or directory exist at given uri.
#### Parameters
| Name | Type |
| :------ | :------ |
| `uriString` | `string` |
| `options?` | `Pick`<[`FileOperationOptions`](#fileoperationoptions), ``"mimeType"``\> |
#### Returns
`Promise`<[`DocumentFileDetail`](#documentfiledetail)\>
#### Defined in
[index.tsx:150](https://github.com/jd1378/react-native-saf-x/blob/e0f8106/src/index.tsx#L150)
___
### exists
**exists**(`uriString`): `Promise`<`boolean`\>
Check if there's a document located at the given uri.
#### Parameters
| Name | Type |
| :------ | :------ |
| `uriString` | `string` |
#### Returns
`Promise`<`boolean`\>
#### Defined in
[index.tsx:117](https://github.com/jd1378/react-native-saf-x/blob/e0f8106/src/index.tsx#L117)
___
### getPersistedUriPermissions
**getPersistedUriPermissions**(): `Promise`<`string`[]\>
Returns a list of all the persisted uri permissions.
#### Returns
`Promise`<`string`[]\>
#### Defined in
[index.tsx:186](https://github.com/jd1378/react-native-saf-x/blob/e0f8106/src/index.tsx#L186)
___
### hasPermission
**hasPermission**(`uriString`): `Promise`<`boolean`\>
Check if you have permission to access the uri.
#### Parameters
| Name | Type |
| :------ | :------ |
| `uriString` | `string` |
#### Returns
`Promise`<`boolean`\>
#### Defined in
[index.tsx:112](https://github.com/jd1378/react-native-saf-x/blob/e0f8106/src/index.tsx#L112)
___
### listFiles
**listFiles**(`uriString`): `Promise`<[`DocumentFileDetail`](#documentfiledetail)[]\>
List all files and folders in a directory uri.
#### Parameters
| Name | Type |
| :------ | :------ |
| `uriString` | `string` |
#### Returns
`Promise`<[`DocumentFileDetail`](#documentfiledetail)[]\>
#### Defined in
[index.tsx:196](https://github.com/jd1378/react-native-saf-x/blob/e0f8106/src/index.tsx#L196)
___
### mkdir
**mkdir**(`uriString`): `Promise`<[`DocumentFileDetail`](#documentfiledetail)\>
Create a directory at given uri.
Automatically creates folders in path if needed.
You can use it to create nested directories easily.
Rejects if it fails.
#### Parameters
| Name | Type |
| :------ | :------ |
| `uriString` | `string` |
#### Returns
`Promise`<[`DocumentFileDetail`](#documentfiledetail)\>
#### Defined in
[index.tsx:172](https://github.com/jd1378/react-native-saf-x/blob/e0f8106/src/index.tsx#L172)
___
### moveFile
**moveFile**(`srcUri`, `destUri`, `options?`): `Promise`<``null`` \| [`DocumentFileDetail`](#documentfiledetail)\>
Move file from source uri to destination uri.
promise Rejects if destination already exists and `replaceIfDestinationExists` option is not set to true.
Does not support moving directories.
#### Parameters
| Name | Type |
| :------ | :------ |
| `srcUri` | `string` |
| `destUri` | `string` |
| `options?` | `FileTransferOptions` |
#### Returns
`Promise`<``null`` \| [`DocumentFileDetail`](#documentfiledetail)\>
#### Defined in
[index.tsx:229](https://github.com/jd1378/react-native-saf-x/blob/e0f8106/src/index.tsx#L229)
___
### openDocument
**openDocument**(`persist`): `Promise`<``null`` \| [`DocumentFileDetail`](#documentfiledetail)\>
Open the Document Picker to select a file.
Returns an object of type `DocumentFileDetail` or `null` if user did not select a file.
#### Parameters
| Name | Type |
| :------ | :------ |
| `persist` | `boolean` |
#### Returns
`Promise`<``null`` \| [`DocumentFileDetail`](#documentfiledetail)\>
#### Defined in
[index.tsx:97](https://github.com/jd1378/react-native-saf-x/blob/e0f8106/src/index.tsx#L97)
___
### openDocumentTree
**openDocumentTree**(`persist`): `Promise`<``null`` \| [`DocumentFileDetail`](#documentfiledetail)\>
Open the Document Picker to select a folder. Read/Write Permission will be granted to the selected folder.
Returns an object of type `DocumentFileDetail` or `null` if user did not select a folder.
#### Parameters
| Name | Type |
| :------ | :------ |
| `persist` | `boolean` |
#### Returns
`Promise`<``null`` \| [`DocumentFileDetail`](#documentfiledetail)\>
#### Defined in
[index.tsx:89](https://github.com/jd1378/react-native-saf-x/blob/e0f8106/src/index.tsx#L89)
___
### readFile
**readFile**(`uriString`, `options?`): `Promise`<`string`\>
Read contents of the given uri. uri must point to a file.
#### Parameters
| Name | Type |
| :------ | :------ |
| `uriString` | `string` |
| `options?` | `Pick`<[`FileOperationOptions`](#fileoperationoptions), ``"encoding"``\> |
#### Returns
`Promise`<`string`\>
#### Defined in
[index.tsx:122](https://github.com/jd1378/react-native-saf-x/blob/e0f8106/src/index.tsx#L122)
___
### releasePersistableUriPermission
**releasePersistableUriPermission**(`uriString`): `Promise`<`void`\>
Remove a uri from persisted uri permissions list.
#### Parameters
| Name | Type |
| :------ | :------ |
| `uriString` | `string` |
#### Returns
`Promise`<`void`\>
#### Defined in
[index.tsx:191](https://github.com/jd1378/react-native-saf-x/blob/e0f8106/src/index.tsx#L191)
___
### rename
**rename**(`uriString`, `newName`): `Promise`<`boolean`\>
Renames the document at given uri.
uri can be file or folder.
Resolves with `true` if successful and `false` otherwise.
#### Parameters
| Name | Type |
| :------ | :------ |
| `uriString` | `string` |
| `newName` | `string` |
#### Returns
`Promise`<`boolean`\>
#### Defined in
[index.tsx:181](https://github.com/jd1378/react-native-saf-x/blob/e0f8106/src/index.tsx#L181)
___
### stat
**stat**(`uriString`): `Promise`<[`DocumentFileDetail`](#documentfiledetail)\>
Get details for a file/directory at given uri.
#### Parameters
| Name | Type |
| :------ | :------ |
| `uriString` | `string` |
#### Returns
`Promise`<[`DocumentFileDetail`](#documentfiledetail)\>
#### Defined in
[index.tsx:201](https://github.com/jd1378/react-native-saf-x/blob/e0f8106/src/index.tsx#L201)
___
### unlink
**unlink**(`uriString`): `Promise`<`boolean`\>
Removes the file or directory at given uri.
Resolves with `true` if delete is successful, `false` otherwise.
#### Parameters
| Name | Type |
| :------ | :------ |
| `uriString` | `string` |
#### Returns
`Promise`<`boolean`\>
#### Defined in
[index.tsx:162](https://github.com/jd1378/react-native-saf-x/blob/e0f8106/src/index.tsx#L162)
___
### writeFile
**writeFile**(`uriString`, `data`, `options?`): `Promise`<`string`\>
Writes the given data to the file at given uri.
Tries to create the file if does not already exist before writing to it.
Resolves with given uriString if successful.
#### Parameters
| Name | Type |
| :------ | :------ |
| `uriString` | `string` |
| `data` | `string` |
| `options?` | [`FileOperationOptions`](#fileoperationoptions) |
#### Returns
`Promise`<`string`\>
#### Defined in
[index.tsx:136](https://github.com/jd1378/react-native-saf-x/blob/e0f8106/src/index.tsx#L136)
## Caveats
Due to simplyifing the uri structure usage, file and directories should not have the same name at a given uri.
doing so can cause unexpected results.
for example in a folder named "foo", do not create "bar" file and "bar" directory making the uri being "foo/bar" for both cases.
___
## Thanks to
- [ammarahm-ed](https://github.com/ammarahm-ed) for his work on [react-native-scoped-storage](https://github.com/ammarahm-ed/react-native-scoped-storage)
which helped me jump start this module.
## Contributing
See the [contributing guide](CONTRIBUTING.md) to learn how to contribute to the repository and the development workflow.
## License
MIT

View File

@ -0,0 +1,60 @@
buildscript {
if (project == rootProject) {
repositories {
google()
mavenCentral()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:4.2.2'
}
}
}
apply plugin: 'com.android.library'
def safeExtGet(prop, fallback) {
rootProject.ext.has(prop) ? rootProject.ext.get(prop) : fallback
}
android {
compileSdkVersion safeExtGet('SafX_compileSdkVersion', 30)
defaultConfig {
minSdkVersion safeExtGet('SafX_minSdkVersion', 21)
targetSdkVersion safeExtGet('SafX_targetSdkVersion', 30)
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
}
}
lintOptions {
disable 'GradleCompatible'
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
repositories {
mavenLocal()
maven {
// All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
url("$rootDir/../node_modules/react-native/android")
}
google()
mavenCentral()
jcenter()
}
dependencies {
//noinspection GradleDynamicVersion
implementation "com.facebook.react:react-native:+" // From node_modules
implementation 'androidx.documentfile:documentfile:1.0.1'
}

View File

@ -0,0 +1 @@
android.useAndroidX=true

View File

@ -0,0 +1,185 @@
#!/usr/bin/env sh
#
# Copyright 2015 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=`expr $i + 1`
done
case $i in
0) set -- ;;
1) set -- "$args0" ;;
2) set -- "$args0" "$args1" ;;
3) set -- "$args0" "$args1" "$args2" ;;
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=`save "$@"`
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
exec "$JAVACMD" "$@"

View File

@ -0,0 +1,89 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@ -0,0 +1,4 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.reactnativesafx">
</manifest>

View File

@ -0,0 +1,55 @@
package androidx.documentfile.provider;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.DocumentsContract;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.reactnativesafx.SafXModule;
public class DocumentFileHelper {
// https://www.reddit.com/r/androiddev/comments/orytnx/fixing_treedocumentfilefindfile_lousy_performance/
@Nullable
public static DocumentFile findFile(
Context context, @NonNull DocumentFile documentFile, @NonNull String displayName) {
if (!(documentFile instanceof TreeDocumentFile)) {
return documentFile.findFile(displayName);
}
final ContentResolver resolver = context.getContentResolver();
final Uri childrenUri =
DocumentsContract.buildChildDocumentsUriUsingTree(
documentFile.getUri(), DocumentsContract.getDocumentId(documentFile.getUri()));
try (Cursor c =
resolver.query(
childrenUri,
new String[] {
DocumentsContract.Document.COLUMN_DOCUMENT_ID,
DocumentsContract.Document.COLUMN_DISPLAY_NAME,
},
null,
null,
null)) {
if (c != null) {
while (c.moveToNext()) {
if (displayName.equals(c.getString(1))) {
return new TreeDocumentFile(
documentFile,
context,
DocumentsContract.buildDocumentUriUsingTree(documentFile.getUri(), c.getString(0)));
}
}
}
} catch (Exception e) {
Log.w(SafXModule.NAME, "query failed: " + e);
}
return null;
}
}

View File

@ -0,0 +1,265 @@
package com.reactnativesafx;
import android.content.Intent;
import android.net.Uri;
import android.os.Build.VERSION_CODES;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.documentfile.provider.DocumentFile;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.module.annotations.ReactModule;
import com.reactnativesafx.utils.DocumentHelper;
import com.reactnativesafx.utils.GeneralHelper;
import com.reactnativesafx.utils.UriHelper;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
@RequiresApi(api = VERSION_CODES.Q)
@ReactModule(name = SafXModule.NAME)
public class SafXModule extends ReactContextBaseJavaModule {
public static final String NAME = "SafX";
private final DocumentHelper documentHelper;
public SafXModule(ReactApplicationContext reactContext) {
super(reactContext);
this.documentHelper = new DocumentHelper(reactContext);
}
@Override
@NonNull
public String getName() {
return NAME;
}
@ReactMethod
public void openDocumentTree(final boolean persist, final Promise promise) {
this.documentHelper.openDocumentTree(persist, promise);
}
@ReactMethod
public void openDocument(final boolean persist, final Promise promise) {
this.documentHelper.openDocument(persist, promise);
}
@ReactMethod
public void createDocument(
final String data,
final String encoding,
final String initialName,
final String mimeType,
final Promise promise) {
this.documentHelper.createDocument(data, encoding, initialName, mimeType, promise);
}
@ReactMethod
public void hasPermission(String uriString, final Promise promise) {
if (this.documentHelper.hasPermission(uriString)) {
promise.resolve(true);
} else {
promise.resolve(false);
}
}
@ReactMethod
public void exists(String uriString, final Promise promise) {
try {
promise.resolve(this.documentHelper.exists(uriString));
} catch (Exception e) {
promise.reject("ERROR", e.getLocalizedMessage());
}
}
@ReactMethod
public void readFile(String uriString, String encoding, final Promise promise) {
try {
DocumentFile file;
try {
file = this.documentHelper.goToDocument(uriString, false, true);
} catch (FileNotFoundException e) {
promise.reject("ENOENT", "'" + uriString + "' does not exist");
return;
}
if (encoding != null) {
if (encoding.equals("ascii")) {
WritableArray arr =
(WritableArray) this.documentHelper.readFromUri(file.getUri(), encoding);
promise.resolve((arr));
} else {
promise.resolve(this.documentHelper.readFromUri(file.getUri(), encoding));
}
} else {
promise.resolve(this.documentHelper.readFromUri(file.getUri(), "utf8"));
}
} catch (Exception e) {
promise.reject("EUNSPECIFIED", e.getLocalizedMessage());
}
}
@ReactMethod
public void writeFile(
String uriString,
String data,
String encoding,
String mimeType,
boolean append,
final Promise promise) {
try {
DocumentFile file;
try {
file = this.documentHelper.goToDocument(uriString, false, true);
} catch (FileNotFoundException e) {
file = this.documentHelper.createFile(uriString, mimeType);
}
byte[] bytes = GeneralHelper.stringToBytes(data, encoding);
try (OutputStream fout =
this.getReactApplicationContext()
.getContentResolver()
.openOutputStream(file.getUri(), append ? "wa" : "wt")) {
fout.write(bytes);
}
promise.resolve(uriString);
} catch (Exception e) {
promise.reject("EUNSPECIFIED", e.getLocalizedMessage());
}
}
@ReactMethod
public void transferFile(
String srcUri, String destUri, boolean replaceIfDestExists, boolean copy, Promise promise) {
this.documentHelper.transferFile(srcUri, destUri, replaceIfDestExists, copy, promise);
}
@ReactMethod
public void rename(String uriString, String newName, final Promise promise) {
try {
DocumentFile doc;
try {
doc = this.documentHelper.goToDocument(uriString, false, true);
} catch (FileNotFoundException e) {
promise.reject("ENOENT", "'" + uriString + "' does not exist");
return;
}
if (doc.renameTo(newName)) {
promise.resolve(true);
} else {
promise.resolve(false);
}
} catch (Exception e) {
promise.reject("EUNSPECIFIED", e.getLocalizedMessage());
}
}
@ReactMethod
public void unlink(String uriString, final Promise promise) {
try {
DocumentFile doc = this.documentHelper.goToDocument(uriString, false, true);
boolean result = doc.delete();
promise.resolve(result);
} catch (FileNotFoundException e) {
promise.reject("ENOENT", e.getLocalizedMessage());
} catch (SecurityException e) {
promise.reject("EPERM", e.getLocalizedMessage());
} catch (Exception e) {
promise.reject("EUNSPECIFIED", e.getLocalizedMessage());
}
}
@ReactMethod
public void mkdir(String uriString, final Promise promise) {
try {
DocumentFile dir = this.documentHelper.mkdir(uriString);
DocumentHelper.resolveWithDocument(dir, promise, uriString);
} catch (IOException e) {
promise.reject("EEXIST", e.getLocalizedMessage());
} catch (SecurityException e) {
promise.reject("EPERM", e.getLocalizedMessage());
} catch (Exception e) {
promise.reject("EUNSPECIFIED", e.getLocalizedMessage());
}
}
@ReactMethod
public void createFile(String uriString, String mimeType, final Promise promise) {
try {
DocumentFile createdFile = this.documentHelper.createFile(uriString, mimeType);
DocumentHelper.resolveWithDocument(createdFile, promise, uriString);
} catch (Exception e) {
promise.reject("EUNSPECIFIED", e.getLocalizedMessage());
}
}
@ReactMethod
public void getPersistedUriPermissions(final Promise promise) {
String[] uriList =
getReactApplicationContext().getContentResolver().getPersistedUriPermissions().stream()
.map(uriPermission -> uriPermission.getUri().toString())
.toArray(String[]::new);
WritableArray wa = Arguments.fromArray(uriList);
promise.resolve(wa);
}
@ReactMethod
public void releasePersistableUriPermission(String uriString, final Promise promise) {
Uri uriToRevoke = Uri.parse(UriHelper.normalize(uriString));
final int takeFlags =
(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
this.getReactApplicationContext()
.getContentResolver()
.releasePersistableUriPermission(uriToRevoke, takeFlags);
promise.resolve(null);
}
@ReactMethod
public void listFiles(String uriString, final Promise promise) {
try {
DocumentFile doc = this.documentHelper.goToDocument(uriString, false, true);
WritableMap[] resolvedDocs =
Arrays.stream(doc.listFiles())
.map(
docEntry ->
DocumentHelper.resolveWithDocument(
docEntry, null, uriString + "/" + docEntry.getName()))
.toArray(WritableMap[]::new);
WritableArray resolveData = Arguments.fromJavaArgs(resolvedDocs);
promise.resolve(resolveData);
} catch (FileNotFoundException e) {
promise.reject("ENOENT", e.getLocalizedMessage());
} catch (SecurityException e) {
promise.reject("EPERM", e.getLocalizedMessage());
} catch (Exception e) {
promise.reject("EUNSPECIFIED", e.getLocalizedMessage());
}
}
@ReactMethod
public void stat(String uriString, final Promise promise) {
try {
DocumentFile doc = this.documentHelper.goToDocument(uriString, false, true);
DocumentHelper.resolveWithDocument(doc, promise, uriString);
} catch (FileNotFoundException e) {
promise.reject("ENOENT", e.getLocalizedMessage());
} catch (SecurityException e) {
promise.reject("EPERM", e.getLocalizedMessage());
} catch (Exception e) {
promise.reject("EUNSPECIFIED", e.getLocalizedMessage());
}
}
}

View File

@ -0,0 +1,28 @@
package com.reactnativesafx;
import androidx.annotation.NonNull;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class SafXPackage implements ReactPackage {
@NonNull
@Override
public List<NativeModule> createNativeModules(@NonNull ReactApplicationContext reactContext) {
List<NativeModule> modules = new ArrayList<>();
modules.add(new SafXModule(reactContext));
return modules;
}
@NonNull
@Override
public List<ViewManager> createViewManagers(@NonNull ReactApplicationContext reactContext) {
return Collections.emptyList();
}
}

View File

@ -0,0 +1,493 @@
package com.reactnativesafx.utils;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.UriPermission;
import android.net.Uri;
import android.os.Build;
import android.os.Build.VERSION_CODES;
import android.util.Base64;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.documentfile.provider.DocumentFile;
import androidx.documentfile.provider.DocumentFileHelper;
import com.facebook.react.bridge.ActivityEventListener;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableMap;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
@RequiresApi(api = VERSION_CODES.Q)
public class DocumentHelper {
private static final int DOCUMENT_TREE_REQUEST_CODE = 1;
private static final int DOCUMENT_REQUEST_CODE = 2;
private static final int DOCUMENT_CREATE_CODE = 3;
private final ReactApplicationContext context;
private ActivityEventListener activityEventListener;
public DocumentHelper(ReactApplicationContext context) {
this.context = context;
}
public void openDocumentTree(final boolean persist, final Promise promise) {
try {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_OPEN_DOCUMENT_TREE);
if (activityEventListener != null) {
context.removeActivityEventListener(activityEventListener);
activityEventListener = null;
}
activityEventListener =
new ActivityEventListener() {
@SuppressLint("WrongConstant")
@Override
public void onActivityResult(
Activity activity, int requestCode, int resultCode, Intent intent) {
if (requestCode == DOCUMENT_TREE_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
if (intent != null) {
Uri uri = intent.getData();
if (persist) {
final int takeFlags =
intent.getFlags()
& (Intent.FLAG_GRANT_READ_URI_PERMISSION
| Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
context.getContentResolver().takePersistableUriPermission(uri, takeFlags);
}
try {
DocumentFile doc = goToDocument(uri.toString(), false);
resolveWithDocument(doc, promise, uri.toString());
} catch (Exception e) {
promise.resolve(null);
}
} else {
promise.resolve(null);
}
} else {
promise.resolve(null);
}
context.removeActivityEventListener(activityEventListener);
activityEventListener = null;
}
@Override
public void onNewIntent(Intent intent) {}
};
context.addActivityEventListener(activityEventListener);
Activity activity = context.getCurrentActivity();
if (activity != null) {
activity.startActivityForResult(intent, DOCUMENT_TREE_REQUEST_CODE);
} else {
promise.reject("ERROR", "Cannot get current activity, so cannot launch document picker");
}
} catch (Exception e) {
promise.reject("ERROR", e.getMessage());
}
}
public void openDocument(final boolean persist, final Promise promise) {
try {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
if (activityEventListener != null) {
context.removeActivityEventListener(activityEventListener);
activityEventListener = null;
}
activityEventListener =
new ActivityEventListener() {
@SuppressLint("WrongConstant")
@Override
public void onActivityResult(
Activity activity, int requestCode, int resultCode, Intent intent) {
if (requestCode == DOCUMENT_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
if (intent != null) {
Uri uri = intent.getData();
if (persist) {
final int takeFlags =
intent.getFlags()
& (Intent.FLAG_GRANT_READ_URI_PERMISSION
| Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
context.getContentResolver().takePersistableUriPermission(uri, takeFlags);
}
try {
DocumentFile doc = goToDocument(uri.toString(), false);
resolveWithDocument(doc, promise, uri.toString());
} catch (Exception e) {
promise.resolve(null);
}
} else {
promise.resolve(null);
}
} else {
promise.resolve(null);
}
context.removeActivityEventListener(activityEventListener);
activityEventListener = null;
}
@Override
public void onNewIntent(Intent intent) {}
};
context.addActivityEventListener(activityEventListener);
Activity activity = context.getCurrentActivity();
if (activity != null) {
activity.startActivityForResult(intent, DOCUMENT_REQUEST_CODE);
} else {
promise.reject("ERROR", "Cannot get current activity, so cannot launch document picker");
}
} catch (Exception e) {
promise.reject("ERROR", e.getMessage());
}
}
public void createDocument(
final String data,
final String encoding,
final String initialName,
final String mimeType,
final Promise promise) {
try {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_CREATE_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
if (initialName != null) {
intent.putExtra(Intent.EXTRA_TITLE, initialName);
}
if (mimeType != null) {
intent.setType(mimeType);
} else {
intent.setType("*/*");
}
if (activityEventListener != null) {
context.removeActivityEventListener(activityEventListener);
activityEventListener = null;
}
activityEventListener =
new ActivityEventListener() {
@Override
public void onActivityResult(
Activity activity, int requestCode, int resultCode, Intent intent) {
if (requestCode == DOCUMENT_CREATE_CODE && resultCode == Activity.RESULT_OK) {
if (intent != null) {
Uri uri = intent.getData();
DocumentFile doc = DocumentFile.fromSingleUri(context, uri);
try {
byte[] bytes = GeneralHelper.stringToBytes(data, encoding);
try (OutputStream os = context.getContentResolver().openOutputStream(uri)) {
os.write(bytes);
}
assert doc != null;
resolveWithDocument(doc, promise, uri.toString());
} catch (Exception e) {
promise.reject("ERROR", e.getLocalizedMessage());
}
} else {
promise.resolve(null);
}
} else {
promise.resolve(null);
}
context.removeActivityEventListener(activityEventListener);
activityEventListener = null;
}
@Override
public void onNewIntent(Intent intent) {}
};
context.addActivityEventListener(activityEventListener);
Activity activity = context.getCurrentActivity();
if (activity != null) {
activity.startActivityForResult(intent, DOCUMENT_CREATE_CODE);
} else {
promise.reject("ERROR", "Cannot get current activity, so cannot launch document picker");
}
} catch (Exception e) {
promise.reject("ERROR", e.getMessage());
}
}
@RequiresApi(api = Build.VERSION_CODES.Q)
@SuppressWarnings({"UnusedDeclaration", "UnusedAssignment"})
public Object readFromUri(Uri uri, String encoding) throws IOException {
byte[] bytes;
int bytesRead;
int length;
InputStream inputStream = context.getContentResolver().openInputStream(uri);
length = inputStream.available();
bytes = new byte[length];
bytesRead = inputStream.read(bytes);
inputStream.close();
switch (encoding.toLowerCase()) {
case "base64":
return Base64.encodeToString(bytes, Base64.NO_WRAP);
case "ascii":
WritableArray asciiResult = Arguments.createArray();
for (byte b : bytes) {
asciiResult.pushInt(b);
}
return asciiResult;
case "utf8":
default:
return new String(bytes);
}
}
public boolean exists(final String uriString) {
return this.exists(uriString, false);
}
public boolean exists(final String uriString, final boolean shouldBeFile) {
try {
DocumentFile fileOrFolder = goToDocument(uriString, false);
if (shouldBeFile) {
return !fileOrFolder.isDirectory();
}
return true;
} catch (Exception e) {
return false;
}
}
public boolean hasPermission(String uriString) {
// list of all persisted permissions for our app
List<UriPermission> uriList = context.getContentResolver().getPersistedUriPermissions();
for (UriPermission uriPermission : uriList) {
if (permissionMatchesAndHasAccess(uriPermission, UriHelper.normalize(uriString))) {
return true;
}
}
return false;
}
public boolean permissionMatchesAndHasAccess(
UriPermission permission, String normalizedUriString) {
String permittedUri = permission.getUri().toString();
return (permittedUri.startsWith(normalizedUriString)
|| normalizedUriString.startsWith(permittedUri))
&& permission.isReadPermission()
&& permission.isWritePermission();
}
private String getPermissionErrorMsg(final String uriString) {
return "You don't have read/write permission to access uri: " + uriString;
}
public static WritableMap resolveWithDocument(
@NonNull DocumentFile file, Promise promise, String SimplifiedUri) {
WritableMap fileMap = Arguments.createMap();
fileMap.putString("uri", UriHelper.denormalize(SimplifiedUri));
fileMap.putString("name", file.getName());
fileMap.putString("type", file.isDirectory() ? "directory" : "file");
if (file.isFile()) {
fileMap.putString("mime", file.getType());
fileMap.putDouble("size", file.length());
}
fileMap.putDouble("lastModified", file.lastModified());
if (promise != null) {
promise.resolve(fileMap);
}
return fileMap;
}
public DocumentFile mkdir(String uriString)
throws IOException, SecurityException, IllegalArgumentException {
return this.mkdir(uriString, true);
}
/**
* @return a DocumentFile that is created using DocumentFile.fromTreeUri()
*/
public DocumentFile mkdir(String uriString, boolean includeLastSegment)
throws IOException, SecurityException, IllegalArgumentException {
DocumentFile dir = goToDocument(uriString, true, includeLastSegment);
assert dir != null;
return dir;
}
public DocumentFile createFile(String uriString) throws IOException, SecurityException {
return createFile(uriString, null);
}
public DocumentFile createFile(String uriString, String mimeType)
throws IOException, SecurityException {
if (this.exists(uriString)) {
throw new IOException("a file or directory already exist at: " + uriString);
}
DocumentFile parentDirOfFile = this.mkdir(uriString, false);
// it should be safe because user cannot select sd root or primary root
// and any other path would have at least one '/' to provide a file name in a folder
String fileName = UriHelper.getLastSegment(uriString);
if (fileName.indexOf(':') != -1) {
throw new IOException(
"Invalid file name: Could not extract filename from uri string provided");
}
DocumentFile createdFile =
parentDirOfFile.createFile(
mimeType != null && !mimeType.equals("") ? mimeType : "*/*", fileName);
if (createdFile == null) {
throw new IOException(
"File creation failed without any specific error for '" + fileName + "'");
}
return createdFile;
}
public DocumentFile goToDocument(String uriString, boolean createIfDirectoryNotExist)
throws SecurityException, IOException {
return goToDocument(uriString, createIfDirectoryNotExist, true);
}
public DocumentFile goToDocument(
String unknownUriString, boolean createIfDirectoryNotExist, boolean includeLastSegment)
throws SecurityException, IOException {
String uriString = UriHelper.normalize(unknownUriString);
String baseUri = "";
String appendUri;
String[] strings = new String[0];
List<UriPermission> uriList = context.getContentResolver().getPersistedUriPermissions();
for (UriPermission uriPermission : uriList) {
String uriPath = uriPermission.getUri().toString();
if (this.permissionMatchesAndHasAccess(uriPermission, uriString)) {
baseUri = uriPath;
appendUri = Uri.decode(uriString.substring(uriPath.length()));
strings = appendUri.split("/");
break;
}
}
if (baseUri.equals("")) {
throw new SecurityException(getPermissionErrorMsg(uriString));
}
if (baseUri.matches("^content://[\\w.]+/document/.*")) {
// It's a document picked by user
DocumentFile doc = DocumentFile.fromSingleUri(context, Uri.parse(uriString));
if (doc != null && doc.isFile() && doc.exists()) {
return doc;
} else {
throw new FileNotFoundException(
"Cannot find the given document. File does not exist at '" + uriString + "'");
}
}
Uri uri = Uri.parse(baseUri);
DocumentFile dir = DocumentFile.fromTreeUri(context, uri);
int pathSegmentsToTraverseLength = includeLastSegment ? strings.length : strings.length - 1;
for (int i = 0; i < pathSegmentsToTraverseLength; i++) {
if (!strings[i].equals("")) {
assert dir != null;
DocumentFile childDoc = DocumentFileHelper.findFile(context, dir, strings[i]);
if (childDoc != null) {
if (childDoc.isDirectory()) {
dir = childDoc;
} else if (i == pathSegmentsToTraverseLength - 1) {
// we are at the last part to traverse, its our destination, doesn't matter if its a
// file or directory
dir = childDoc;
} else {
// child doc is a file
throw new IOException(
"There's a document with the same name as the one we are trying to traverse at: '"
+ childDoc.getUri()
+ "'");
}
} else {
if (createIfDirectoryNotExist) {
dir = dir.createDirectory(strings[i]);
} else {
throw new FileNotFoundException(
"Cannot traverse to the pointed document. Directory '"
+ strings[i]
+ "'"
+ " does not exist in '"
+ dir.getUri()
+ "'");
}
}
}
}
assert dir != null;
return dir;
}
public void transferFile(
String srcUri, String destUri, boolean replaceIfDestExists, boolean copy, Promise promise) {
try {
DocumentFile srcDoc = this.goToDocument(srcUri, false, true);
if (srcDoc.isDirectory()) {
throw new IllegalArgumentException("Cannot move directories");
}
DocumentFile destDoc;
try {
destDoc = this.goToDocument(destUri, false, true);
if (!replaceIfDestExists) {
throw new IOException("a document with the same name already exists in destination");
}
} catch (FileNotFoundException e) {
destDoc = this.createFile(destUri, srcDoc.getType());
}
try (InputStream inStream =
this.context.getContentResolver().openInputStream(srcDoc.getUri());
OutputStream outStream =
this.context.getContentResolver().openOutputStream(destDoc.getUri(), "wt"); ) {
byte[] buffer = new byte[1024 * 4];
int length;
while ((length = inStream.read(buffer)) > 0) {
outStream.write(buffer, 0, length);
}
}
if (!copy) {
srcDoc.delete();
}
promise.resolve(resolveWithDocument(destDoc, promise, destUri));
} catch (Exception e) {
promise.reject("EUNSPECIFIED", e.getLocalizedMessage());
}
}
}

View File

@ -0,0 +1,26 @@
package com.reactnativesafx.utils;
import android.util.Base64;
import java.nio.charset.StandardCharsets;
public class GeneralHelper {
/**
* String to byte converter method
*
* @param data Raw data in string format
* @param encoding Decoder name
* @return Converted data byte array
*/
public static byte[] stringToBytes(String data, String encoding) {
if (encoding != null) {
if (encoding.equalsIgnoreCase("ascii")) {
return data.getBytes(StandardCharsets.US_ASCII);
} else if (encoding.toLowerCase().contains("base64")) {
return Base64.decode(data, Base64.NO_WRAP);
} else if (encoding.equalsIgnoreCase("utf8")) {
return data.getBytes(StandardCharsets.UTF_8);
}
}
return data.getBytes(StandardCharsets.UTF_8);
}
}

View File

@ -0,0 +1,36 @@
package com.reactnativesafx.utils;
import android.net.Uri;
import android.os.Build.VERSION_CODES;
import androidx.annotation.RequiresApi;
@RequiresApi(api = VERSION_CODES.Q)
public class UriHelper {
public static final String CONTENT_URI_PREFIX = "content://";
public static String getLastSegment(String uriString) {
return Uri.parse(Uri.decode(uriString)).getLastPathSegment();
}
public static String normalize(String uriString) {
// an abnormal uri example:
// content://com.android.externalstorage.documents/tree/1707-3F0B%3Ajoplin/locks/2_2_fa4f9801e9a545a58f1a6c5d3a7cfded.json
// normalized:
// content://com.android.externalstorage.documents/tree/1707-3F0B%3Ajoplin%2Flocks%2F2_2_fa4f9801e9a545a58f1a6c5d3a7cfded.json
// uri parts:
String[] parts = Uri.decode(uriString).split(":");
return parts[0] + ":" + parts[1] + Uri.encode(":" + parts[2]);
}
public static String denormalize(String uriString) {
// an normalized uri example:
// content://com.android.externalstorage.documents/tree/1707-3F0B%3Ajoplin%2Flocks%2F2_2_fa4f9801e9a545a58f1a6c5d3a7cfded.json
// denormalized:
// content://com.android.externalstorage.documents/tree/1707-3F0B/Ajoplin/locks/2_2_fa4f9801e9a545a58f1a6c5d3a7cfded.json
return Uri.decode(normalize(uriString));
}
}

View File

@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.8-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

View File

@ -0,0 +1,14 @@
module.exports = {
source: 'src',
output: 'lib',
targets: [
'commonjs',
'module',
[
'typescript',
{
project: 'tsconfig.build.json',
},
],
],
};

View File

@ -0,0 +1,11 @@
// Sync object
/** @type {import('@jest/types').Config.InitialOptions} */
const config = {
preset: 'react-native',
modulePathIgnorePatterns: [
'<rootDir>/example/node_modules',
'<rootDir>/lib/',
],
};
module.exports = config;

View File

@ -0,0 +1,56 @@
{
"name": "@joplin/react-native-saf-x",
"version": "0.5.2",
"description": "a module to help work with scoped storages on android easily",
"main": "src/index",
"react-native": "src/index",
"source": "src/index",
"files": [
"src",
"lib",
"android",
"ios",
"cpp",
"react-native-saf-x.podspec",
"!lib/typescript/example",
"!android/build",
"!ios/build",
"!**/__tests__",
"!**/__fixtures__",
"!**/__mocks__"
],
"scripts": {
"test": "jest",
"linter-precommit": "yarn --cwd ../../ eslint --resolve-plugins-relative-to . --fix packages/react-native-saf-x/**/*.{js,ts,tsx}",
"tsc": "tsc --project tsconfig.json"
},
"keywords": [
"react-native",
"android",
"scoped-storage",
"scoped",
"storage",
"SAF",
"storage-access-framework"
],
"author": "Javad Mnjd (https://github.com/jd1378)",
"license": "MIT",
"homepage": "",
"publishConfig": {
"access": "public"
},
"devDependencies": {
"@babel/core": "^7.12.9",
"@types/jest": "^26.0.15",
"@types/react": "^16.9.55",
"@types/react-native": "^0.64.4",
"jest": "^26.6.3",
"react": "17.0.2",
"react-native": "0.66.1",
"typescript": "^4.0.5"
},
"peerDependencies": {
"react": "*",
"react-native": "*"
}
}

View File

@ -0,0 +1,19 @@
require "json"
package = JSON.parse(File.read(File.join(__dir__, "package.json")))
Pod::Spec.new do |s|
s.name = "react-native-saf-x"
s.version = package["version"]
s.summary = package["description"]
s.homepage = package["homepage"]
s.license = package["license"]
s.authors = package["author"]
s.platforms = { :ios => "10.0" }
s.source = { :git => "https://github.com/jd1378/react-native-saf-x.git", :tag => "#{s.version}" }
s.source_files = "ios/**/*.{h,m,mm}"
s.dependency "React-Core"
end

View File

@ -0,0 +1,29 @@
const os = require('os');
const path = require('path');
const child_process = require('child_process');
const root = path.resolve(__dirname, '..');
const args = process.argv.slice(2);
const options = {
cwd: process.cwd(),
env: process.env,
stdio: 'inherit',
encoding: 'utf-8',
};
if (os.type() === 'Windows_NT') {
options.shell = true;
}
let result;
if (process.cwd() !== root || args.length) {
// We're not in the root of the project, or additional arguments were passed
// In this case, forward the command to `yarn`
result = child_process.spawnSync('yarn', args, options);
} else {
// If `yarn` is run without arguments, perform bootstrap
result = child_process.spawnSync('yarn', ['bootstrap'], options);
}
process.exitCode = result.status;

View File

@ -0,0 +1,264 @@
import { NativeModules, Platform } from 'react-native';
const LINKING_ERROR =
`The package 'react-native-saf-x' doesn't seem to be linked. Make sure: \n\n${
Platform.select({ ios: '- You have run \'pod install\'\n', default: '' })
}- You rebuilt the app after installing the package\n` +
'- You are not using Expo managed workflow\n';
let SafX: SafxInterface;
if (Platform.OS === 'android') {
SafX = (
NativeModules.SafX
? NativeModules.SafX
: new Proxy(
{},
{
get() {
throw new Error(LINKING_ERROR);
},
}
)
) as SafxInterface;
} else {
// @ts-ignore
SafX = {};
}
export type Encoding = 'utf8' | 'base64' | 'ascii';
/** Native interface of the module */
interface SafxInterface {
openDocumentTree(persist: boolean): Promise<DocumentFileDetail | null>;
openDocument(persist: boolean): Promise<DocumentFileDetail | null>;
createDocument(
data: String,
encoding?: String,
initialName?: string,
mimeType?: String,
): Promise<DocumentFileDetail | null>;
hasPermission(uriString: string): Promise<boolean>;
exists(uriString: string): Promise<boolean>;
readFile(uriString: string, encoding?: Encoding): Promise<string>;
writeFile(
uriString: string,
data: string,
encoding?: Encoding,
mimeType?: string,
append?: boolean,
): Promise<string>;
createFile(uriString: string, mimeType?: String): Promise<DocumentFileDetail>;
unlink(uriString: string): Promise<boolean>;
mkdir(uriString: string): Promise<DocumentFileDetail>;
rename(uriString: string, newName: string): Promise<boolean>;
getPersistedUriPermissions(): Promise<Array<string>>;
releasePersistableUriPermission(uriString: string): Promise<void>;
listFiles(uriString: string): Promise<DocumentFileDetail[]>;
stat(uriString: string): Promise<DocumentFileDetail>;
transferFile(
srcUri: string,
destUri: string,
replaceIfDestExist: boolean,
copy: boolean,
): Promise<DocumentFileDetail | null>;
}
export type DocumentFileDetail = {
uri: string;
name: string;
type: 'directory' | 'file';
lastModified: number;
mime?: string;
size?: number;
};
export type FileOperationOptions = {
/** Defaults to `'utf8'` */
encoding?: Encoding;
/** Append data to the file. If not set file content will be overwritten. */
append?: boolean;
/** mime type of the file being saved. Defaults to '\*\/\*' */
mimeType?: string;
};
export type CreateDocumentOptions = FileOperationOptions & {
/** initial display name when opening file picker */
initialName?: string;
};
/**
* Open the Document Picker to select a folder. Read/Write Permission will be granted to the selected folder.
* Returns an object of type `DocumentFileDetail` or `null` if user did not select a folder.
*/
export function openDocumentTree(persist: boolean) {
return SafX.openDocumentTree(persist);
}
/**
* Open the Document Picker to select a file.
* Returns an object of type `DocumentFileDetail` or `null` if user did not select a file.
*/
export function openDocument(persist: boolean) {
return SafX.openDocument(persist);
}
/**
* Open the Document Picker to save a file.
* Returns an object of type `DocumentFileDetail` or `null` if user did not select a file.
*/
export function createDocument(data: string, options?: CreateDocumentOptions) {
if (!options) options = {};
const { encoding, initialName, mimeType } = options;
return SafX.createDocument(data, encoding, initialName, mimeType);
}
/** Check if you have permission to access the uri. */
export function hasPermission(uriString: string) {
return SafX.hasPermission(uriString);
}
/** Check if there's a document located at the given uri. */
export function exists(uriString: string) {
return SafX.exists(uriString);
}
/** Read contents of the given uri. uri must point to a file. */
export function readFile(
uriString: string,
options?: Pick<FileOperationOptions, 'encoding'>
) {
if (!options) options = {};
const { encoding } = options;
return SafX.readFile(uriString, encoding);
}
/**
* Writes the given data to the file at given uri.
* Tries to create the file if does not already exist before writing to it.
* Resolves with given uriString if successful.
*/
export function writeFile(
uriString: string,
data: string,
options?: FileOperationOptions
) {
if (!options) options = {};
const { encoding, append, mimeType } = options;
return SafX.writeFile(uriString, data, encoding, mimeType, !!append);
}
/**
* Creates an empty file at given uri.
* Rejects if a file or directory exist at given uri.
*/
export function createFile(
uriString: string,
options?: Pick<FileOperationOptions, 'mimeType'>
) {
if (!options) options = {};
const { mimeType } = options;
return SafX.createFile(uriString, mimeType);
}
//
// Removes the file or directory at given uri.
// Resolves with `true` if delete is successful, `false` otherwise.
export function unlink(uriString: string) {
return SafX.unlink(uriString);
}
/**
* Create a directory at given uri.
* Automatically creates folders in path if needed.
* You can use it to create nested directories easily.
* Rejects if it fails.
*/
export function mkdir(uriString: string) {
return SafX.mkdir(uriString);
}
/**
* Renames the document at given uri.
* uri can be file or folder.
* Resolves with `true` if successful and `false` otherwise.
*/
export function rename(uriString: string, newName: string) {
return SafX.rename(uriString, newName);
}
/** Returns a list of all the persisted uri permissions. */
export function getPersistedUriPermissions() {
return SafX.getPersistedUriPermissions();
}
/** Remove a uri from persisted uri permissions list. */
export function releasePersistableUriPermission(uriString: string) {
return SafX.releasePersistableUriPermission(uriString);
}
/** List all files and folders in a directory uri. */
export function listFiles(uriString: string) {
return SafX.listFiles(uriString);
}
/** Get details for a file/directory at given uri. */
export function stat(uriString: string) {
return SafX.stat(uriString);
}
type FileTransferOptions = {
replaceIfDestinationExists?: boolean;
};
/**
* Copy file from source uri to destination uri.
* promise Rejects if destination already exists and `replaceIfDestinationExists` option is not set to true.
* Does not support moving directories.
*/
export function copyFile(
srcUri: string,
destUri: string,
options?: FileTransferOptions
) {
if (!options) options = {};
const { replaceIfDestinationExists = false } = options;
return SafX.transferFile(srcUri, destUri, replaceIfDestinationExists, true);
}
/**
* Move file from source uri to destination uri.
* promise Rejects if destination already exists and `replaceIfDestinationExists` option is not set to true.
* Does not support moving directories.
*/
export function moveFile(
srcUri: string,
destUri: string,
options?: FileTransferOptions
) {
if (!options) options = {};
const { replaceIfDestinationExists = false } = options;
return SafX.transferFile(srcUri, destUri, replaceIfDestinationExists, false);
}
export default {
openDocumentTree,
openDocument,
createDocument,
hasPermission,
exists,
readFile,
writeFile,
createFile,
unlink,
mkdir,
rename,
getPersistedUriPermissions,
releasePersistableUriPermission,
listFiles,
stat,
copyFile,
moveFile,
};

View File

@ -0,0 +1,5 @@
{
"extends": "./tsconfig",
"exclude": ["example"]
}

View File

@ -0,0 +1,13 @@
{
"extends": "../../tsconfig.json",
"include": [
"**/*.ts",
"**/*.tsx",
],
"exclude": [
"**/node_modules",
"tests/support/**/*",
"tests-build/**/*",
"build/**/*",
],
}

View File

@ -3276,6 +3276,7 @@ __metadata:
"@codemirror/state": ^6.0.0
"@codemirror/view": ^6.0.0
"@joplin/lib": ~2.8
"@joplin/react-native-saf-x": ~0.5
"@joplin/renderer": ~2.8
"@joplin/tools": ~2.8
"@lezer/highlight": ^1.0.0
@ -3511,6 +3512,24 @@ __metadata:
languageName: unknown
linkType: soft
"@joplin/react-native-saf-x@workspace:packages/react-native-saf-x, @joplin/react-native-saf-x@~0.5":
version: 0.0.0-use.local
resolution: "@joplin/react-native-saf-x@workspace:packages/react-native-saf-x"
dependencies:
"@babel/core": ^7.12.9
"@types/jest": ^26.0.15
"@types/react": ^16.9.55
"@types/react-native": ^0.64.4
jest: ^26.6.3
react: 17.0.2
react-native: 0.66.1
typescript: ^4.0.5
peerDependencies:
react: "*"
react-native: "*"
languageName: unknown
linkType: soft
"@joplin/renderer@^2.8.1, @joplin/renderer@workspace:packages/renderer, @joplin/renderer@~2.8":
version: 0.0.0-use.local
resolution: "@joplin/renderer@workspace:packages/renderer"