profile
viewpoint
If you are wondering where the data of this site comes from, please visit https://api.github.com/users/vonovak/events. GitMemory does not store any data, but only uses NGINX to cache data for a period of time. The idea behind GitMemory is simply to give users a better reading experience.
Vojtech Novak vonovak Prague, Czech Republic https://react-native-training.eu freelance React Native, Java and Objective-C

mobxjs/mobx-state-tree 6091

Full-featured reactive state management without the boilerplate

oblador/react-native-keychain 2251

:key: Keychain Access for React Native

react-native-google-signin/google-signin 2241

Google Sign-in for your React Native applications

react-native-datetimepicker/datetimepicker 1281

React Native date & time picker component for iOS, Android and Windows

rnmods/react-native-document-picker 761

Document Picker for React Native using Document Providers

react-native-dialogs/react-native-dialogs 579

React Native wrappers for https://github.com/afollestad/material-dialogs

vonovak/appcenter-build-scripts-examples 0

A collection of build script examples to be used in the Build service of https://appcenter.ms

pull request commentrnmods/react-native-document-picker

Added pickDirectory implementation for Windows

Totally makes sense and sorry for submitting the PR to the wrong branch! I'll work on it next week. Do you have any preference on the approach among the two you've listed?

qmatteoq

comment created time in a day

release mobxjs/mobx-state-tree

v5.0.2

released time in 2 days

startedvonovak/react-native-simple-toast

started time in 2 days

pull request commentrnmods/react-native-document-picker

Added pickDirectory implementation for Windows

Once this PR is merged, I'll work on adding the Windows implementation of the example which is included

qmatteoq

comment created time in 2 days

PR opened rnmods/react-native-document-picker

Added pickDirectory implementation for Windows

<!-- Thanks for submitting a pull request! We appreciate you spending the time to work on these changes. Please follow the template so that the reviewers can easily understand what the code changes affect -->

Summary

<!-- Explain the motivation for making this change: here are some points to help you:

  • What issues does the pull request solve? Please tag them so that they will get automatically closed once the PR is merged
  • What is the feature? (if applicable)
  • How did you implement the solution?
  • What areas of the library does it impact? -->

This PR provides the pickDirectory() feature implementation for Windows. After selecting a folder from your Windows device, the function will return the full path of the folder.

Test Plan

<!-- Demonstrate the code is solid. Example: The exact commands you ran and their output, screenshots / videos if the pull request changes UI. -->

  1. I've installed the module from my branch on a RNW project
  2. I've added the following function in the App.js file and I've connected it to the onPress event of a Buttoncontrol:
const pickFolder = async () => {
  var res = await DocumentPicker.pickDirectory();
  console.log(res.uri);
}
  1. I've observed the folder picker UI appearing. I've selected a folder.
  2. In the debugger log, I've observed the full path of the selected folder being displayed.

What's required for testing (prerequisites)?

No special prerequisites, other than a React Native application with Windows support.

What are the steps to reproduce (after prerequisites)?

  1. Add the following function in your code:
const pickFolder = async () => {
  var res = await DocumentPicker.pickDirectory();
  console.log(res.uri);
}
  1. Add a Button control in the page which invokes this function when it's pressed.

Compatibility

OS Implemented
Windows

Checklist

<!-- Check completed item, when applicable, via: [X] -->

  • [x] I have tested this on a device and a simulator
  • [x] I added the documentation in README.md
  • [ ] I updated the typed files (TS and Flow)
+30 -4

0 comment

3 changed files

pr created time in 2 days

push eventrnmods/react-native-document-picker

Matteo Pagani

commit sha 82f7d5892a3c4d64484ff60537b3da3d1b98ccc0

Added pickDirectory support for Windows in README

view details

push time in 2 days

push eventrnmods/react-native-document-picker

Matteo Pagani

commit sha bc7b7e43463defd1436a14b8b56f4a82fa4ad385

Added windows as supported platform for pickDirectory

view details

push time in 2 days

push eventrnmods/react-native-document-picker

Matteo Pagani

commit sha 29bf489e5a1cf142f45158680a22400b7c32f8d6

Fixed issue with Dispatcher

view details

push time in 2 days

create barnchrnmods/react-native-document-picker

branch : folder-picker-windows

created branch time in 2 days

pull request commentrnmods/react-native-document-picker

feat: rework module using react native bob

Also, what do you think of the naming? Would you prefer this to be named pickDirectory or selectDirectory or does it not matter in your opinion? Thanks again :)

I like pickDirectory more, since it's consistent with the existing APIs for files ☺

vonovak

comment created time in 2 days

pull request commentrnmods/react-native-document-picker

feat: rework module using react native bob

The way I implemented this feature in Windows is to retrieve a list of all the files in the selected folder, but I realize that this is different from what you have in the other platforms. I will rework the feature to work like on Android and return the path of the selected folder and submit a PR. Enjoy your holidays! 😊

vonovak

comment created time in 2 days

startedvonovak/react-navigation-header-buttons

started time in 3 days

issue commentrnmods/react-native-document-picker

How to get Absolute Path of the file ?

Just tried react-native-sound instead react-native-sound-player. This does indeed seem to work :smiley: . Thanks so much @AbdulBsit!

In case someone else is wondering this is the code that ended up working for me:

const getResolvedPath = async (uri) => {

  const fileBase64 = await ReactNativeBlobUtil.fs.readFile(uri, "base64")
  const relativePath = ReactNativeBlobUtil.fs.dirs.CacheDir
  const fileName = `${Date.now()}.mp3 `
  const path = `${relativePath}/${fileName}`

  // Create temporary file
  await ReactNativeBlobUtil.fs.writeFile(path, fileBase64, "base64")
  return { relativePath, fileName }
}

const accessFile = async () => {
  try {
      const audioRes = await DocumentPicker.pick({
          type: [DocumentPicker.types.audio]
      });

      // Get resolved file uri from temporary file
      const { relativePath, fileName } = await getResolvedPath(audioRes.uri)

      const localAudio = new Sound(fileName, relativePath, (error) => {
          if (error) {
              console.log('failed to load the sound', error);
              return;
          }
          // Loaded audio successfully
          const audioDuration = localAudio.getDuration()
          if (!audioDuration) return; // Audio length could not be estimated
          console.log(audioDuration);
      });
  } catch (err) {
      if (DocumentPicker.isCancel(err)) {
          // User cancelled the picker, exit any dialogs or menus and move on
      } else {
          throw err;
      }
  }

}
ronastlelobo

comment created time in 3 days

issue commentrnmods/react-native-document-picker

How to get Absolute Path of the file ?

@Malthehave , This seems to be a problem with a sound player, I am using https://github.com/zmxv/react-native-sound try this one, check if it fit you case and solve the error

ronastlelobo

comment created time in 3 days

issue commentrnmods/react-native-document-picker

How to get Absolute Path of the file ?

Hi @AbdulBsit. The output of your first getResolvedPath function returns: /data/user/0/com.purplelyd/cache/1623861156744.mp3. So the protocol is neither content:// uri or file:// .

According to the react-native-sound-player docs they manually place the audio files in {project_root}/android/app/src/main/res/raw/ . You don't think this has anything to do with it not working right? Since that won't let a user play a file from their own device.

The complete log of the first getResolvedPath function is as follows:

const getResolvedPath = async (uri) => {
    console.log("uri in: ", uri);

    // step1 read content from file
    const fileBase64 = await ReactNativeBlobUtil.fs.readFile(uri, "base64")
    console.log("fileBase64 out: ", uri);
    const path = `${ReactNativeBlobUtil.fs.dirs.CacheDir}/${Date.now()}.mp3`
    console.log("created path: ", path);

    // step 2 write content to temp file
    await ReactNativeBlobUtil.fs.writeFile(path, fileBase64, "base64")
    const tempFileInfo = await ReactNativeBlobUtil.fs.stat(path)
    console.log("tempFileInfo: ", tempFileInfo);
    return tempFileInfo.path
}
 LOG  uri in:  content://com.android.providers.media.documents/document/audio%3A31
 LOG  fileBase64 out:  content://com.android.providers.media.documents/document/audio%3A31
 LOG  created path:  /data/user/0/com.purplelyd/cache/1623861156744.mp3
 LOG  tempFileInfo:  {"filename": "1623861156744.mp3", "lastModified": 1623861156000, "path": "/data/user/0/com.purplelyd/cache/1623861156744.mp3", "size": 764176, "type": "file"}

Weirdly enough this latest getResolvedPath function:

 const getResolvedPath = async (uri) => {
    const pathToTempFile= `${ReactNativeBlobUtil.fs.dirs.CacheDir}/${Date.now()}.mp3`
    await ReactNativeBlobUtil.fs.createFile(pathToTempFile,uri, 'uri')
    const {path} = await ReactNativeBlobUtil.fs.stat(pathToTempFile)
    return path.startsWith('content://') ? pathToTempFile : path

  }

Gives me an error when calling ReactNativeBlobUtil.fs.stat : [Error: Source file : content://com.android.providers.media.documents/document/audio%3A31 does not exist]. Sort of like the createFile function not creating the file correctly.

*I appreciate you taking time to help me out here 😃

ronastlelobo

comment created time in 4 days

issue commentrnmods/react-native-document-picker

How to get Absolute Path of the file ?

@Malthehave Ooh sorry typo error, I'll update the code, it should be writeFile not write But still you got the error, Strange, it works for me, Can you show me the log the result of temp file returning from, Is it still content://... uri or file://... uri ?

ronastlelobo

comment created time in 4 days

issue commentrnmods/react-native-document-picker

How to get base64 format?

Is there a way to convert the result of documentPicker to base64? I need the base64 to send to my backend.

TamasFarago

comment created time in 4 days

startedvonovak/react-navigation-header-buttons

started time in 4 days

MemberEvent

issue commentrnmods/react-native-document-picker

How to get Absolute Path of the file ?

Thanks so much for your reply @AbdulBsit ! This line: await ReactNativeBlobUtil.fs.write(path, fileBase64, "base64") , gave me an error like so: TypeError: _reactNativeBlobUtil.default.fs.write is not a function..

So I changed it to: await ReactNativeBlobUtil.fs.writeFile(path, fileBase64, "base64")

But unfortunately I still get the error mentioned in this issue: johnsonsu/react-native-sound-player#126 .

I don't know what's going wrong, as it's the same result on my emulator as my physical Android.🤔 . Does the above code work for you?

ronastlelobo

comment created time in 4 days

issue commentrnmods/react-native-document-picker

How to get Absolute Path of the file ?

hey @Malthehave, As it was a work around, so probably it will somehow throw exceptions in cases, I have been facing the same problem since long as mentioned by you https://github.com/johnsonsu/react-native-sound-player/issues/126, So I solved it finally using

  1. read content from the content:// URI returned by document picker as base64
  2. write to temp file using https://github.com/RonRadtke/react-native-blob-util
  3. Get the file uri and use in react-native-sound-player

Usage

import ReactNativeBlobUtil from 'react-native-blob-util'
import DocumentPicker from 'react-native-document-picker';
import SoundPlayer from 'react-native-sound-player'

 const getResolvedPath = async (uri) => {

   // step1 read content from file
    const fileBase64 = await ReactNativeBlobUtil.fs.readFile(uri, "base64")
    const path = `${ReactNativeBlobUtil.fs.dirs.CacheDir}/${Date.now()}.mp3`

    // step 2 write content to temp file
    await ReactNativeBlobUtil.fs.write(path, fileBase64, "base64")
    const tempFileInfo = await ReactNativeBlobUtil.fs.stat(path)
    return tempFileInfo.path
  }

  const accessFile = async () => {
    try {
        const audioRes = await DocumentPicker.pick({
            type: [DocumentPicker.types.audio],
        });

        // get resolved file uri from temporary file
        const soundFileUri=await getResolvedPath(audioRes.uri)

        SoundPlayer.playSoundFile(soundFileUri, 'mp3')        
    } catch (err) {
        if (DocumentPicker.isCancel(err)) {
            // User cancelled the picker, exit any dialogs or menus and move on
        } else {
            throw err;
        }
    }

}

Hope it help!

ronastlelobo

comment created time in 5 days

startedvonovak/react-native-simple-toast

started time in 5 days

issue commentrnmods/react-native-document-picker

How to get Absolute Path of the file ?

Hello @AbdulBsit I tried your function, which returns when logged: {"_U": 0, "_V": 0, "_W": null, "_X": null} And then throws this error: You attempted to set the key_Vwith the value1on an object that is meant to be immutable and has been frozen.

Do you have any idea why this is happening? I'm using the react-native-sound-player library for reference

ronastlelobo

comment created time in 5 days

Pull request review commentrnmods/react-native-document-picker

Android: add pickDirectory

 declare module 'react-native-document-picker' {     ): Promise<DocumentPickerResponse[]>;     static isCancel<IError extends { code?: string }>(err?: IError): boolean;     static releaseSecureAccess(uris: Array<string>): void;+    static pickDirectory(): Promise<DirectoryPickerResponse> | null;

maybe it should just be Promise<string> ? what do you prefer?

roman-r-m

comment created time in 5 days

pull request commentrnmods/react-native-document-picker

Android: add pickDirectory

Ok, thanks. I'll resubmit without the path.

roman-r-m

comment created time in 5 days

PullRequestEvent

startedvonovak/react-native-simple-toast

started time in 6 days

PR closed rnmods/react-native-document-picker

Android: add pickDirectory

Resolves https://github.com/rnmods/react-native-document-picker/issues/302

Adds a method to show system directory picker on Android. Returns the URI of the directory and if possible resolves the URI to the actual path.

  • [x] I have tested this on a device and a simulator
  • [x] I added the documentation in README.md
  • [x] I updated the typed files (TS and Flow)
+107 -5

3 comments

4 changed files

roman-r-m

pr closed time in 6 days

Pull request review commentrnmods/react-native-document-picker

Android: add pickDirectory

 public void onShowActivityResult(int resultCode, Intent data, Promise promise) { 		} 	} +	@ReactMethod+	public void pickDirectory(Promise promise) {+		Activity currentActivity = getCurrentActivity();++		if (currentActivity == null) {+			promise.reject(E_ACTIVITY_DOES_NOT_EXIST, "Current activity does not exist");+			return;+		}+		this.promise = promise;+		try {+			Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);+			currentActivity.startActivityForResult(intent, PICK_DIR_REQUEST_CODE, null);+		} catch (Exception e) {+			sendError(E_FAILED_TO_SHOW_PICKER, "Failed to create directory picker", e);+		}+	}++	private void onPickDirectoryResult(int resultCode, Intent data, Promise promise) {+		if (resultCode == Activity.RESULT_CANCELED) {+			sendError(E_DOCUMENT_PICKER_CANCELED, "User canceled directory picker");+			return;+		} else if (resultCode != Activity.RESULT_OK) {+			sendError(E_UNKNOWN_ACTIVITY_RESULT, "Unknown activity result: " + resultCode);+			return;+		}++		if (data == null || data.getData() == null) {+			sendError(E_INVALID_DATA_RETURNED, "Invalid data returned by intent");+			return;+		}+		Uri uri = data.getData();++		WritableMap map = Arguments.createMap();+		map.putString(FIELD_URI, uri.toString());++		String path = uriToPath(uri);+		if (path != null) {+			map.putString(FIELD_PATH, path);+		}+		promise.resolve(map);+	}++	private String uriToPath(Uri uri) {+		if (ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {+			File file = new File(uri.getPath());+			return file.getName();+		} else if (ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {+			String name = null;++			// URI examples+			// internal: content://com.android.externalstorage.documents/tree/primary%3Atest+			// sd card:  content://com.android.externalstorage.documents/tree/1DEA-0313%3Atest+			List<String> pathSegments = uri.getPathSegments();+			if (pathSegments.get(0).equalsIgnoreCase("tree")) {

The approach taken here seems like a heuristic that works for some cases, but may not work in others so I'm hesitant to merging this. We should be using android-system-provided tools to work with uris.

Ok, fair enough.

roman-r-m

comment created time in 6 days