@vali98/react-native-fs 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/LICENSE +20 -0
  2. package/README.md +46 -0
  3. package/ReactNativeLocalDownload.podspec +26 -0
  4. package/android/build.gradle +100 -0
  5. package/android/generated/java/com/chatterui/reactnativelocaldownload/NativeReactNativeLocalDownloadSpec.java +38 -0
  6. package/android/generated/jni/CMakeLists.txt +36 -0
  7. package/android/generated/jni/RNReactNativeLocalDownloadSpec-generated.cpp +32 -0
  8. package/android/generated/jni/RNReactNativeLocalDownloadSpec.h +31 -0
  9. package/android/generated/jni/react/renderer/components/RNReactNativeLocalDownloadSpec/RNReactNativeLocalDownloadSpecJSI-generated.cpp +27 -0
  10. package/android/generated/jni/react/renderer/components/RNReactNativeLocalDownloadSpec/RNReactNativeLocalDownloadSpecJSI.h +71 -0
  11. package/android/gradle.properties +5 -0
  12. package/android/src/main/AndroidManifest.xml +5 -0
  13. package/android/src/main/AndroidManifestNew.xml +2 -0
  14. package/android/src/main/java/com/chatterui/reactnativelocaldownload/ReactNativeLocalDownloadModule.kt +95 -0
  15. package/android/src/main/java/com/chatterui/reactnativelocaldownload/ReactNativeLocalDownloadPackage.kt +33 -0
  16. package/ios/ReactNativeLocalDownload.h +6 -0
  17. package/ios/ReactNativeLocalDownload.mm +35 -0
  18. package/ios/generated/RNReactNativeLocalDownloadSpec/RNReactNativeLocalDownloadSpec-generated.mm +39 -0
  19. package/ios/generated/RNReactNativeLocalDownloadSpec/RNReactNativeLocalDownloadSpec.h +64 -0
  20. package/ios/generated/RNReactNativeLocalDownloadSpecJSI-generated.cpp +27 -0
  21. package/ios/generated/RNReactNativeLocalDownloadSpecJSI.h +71 -0
  22. package/lib/module/NativeReactNativeLocalDownload.ts +8 -0
  23. package/lib/module/index.js +48 -0
  24. package/lib/module/index.js.map +1 -0
  25. package/lib/module/package.json +1 -0
  26. package/lib/typescript/package.json +1 -0
  27. package/lib/typescript/src/NativeReactNativeLocalDownload.d.ts +7 -0
  28. package/lib/typescript/src/NativeReactNativeLocalDownload.d.ts.map +1 -0
  29. package/lib/typescript/src/index.d.ts +10 -0
  30. package/lib/typescript/src/index.d.ts.map +1 -0
  31. package/package.json +170 -0
  32. package/react-native.config.js +12 -0
  33. package/src/NativeReactNativeLocalDownload.ts +8 -0
  34. package/src/index.tsx +64 -0
package/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Vali98
4
+ Permission is hereby granted, free of charge, to any person obtaining a copy
5
+ of this software and associated documentation files (the "Software"), to deal
6
+ in the Software without restriction, including without limitation the rights
7
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ copies of the Software, and to permit persons to whom the Software is
9
+ furnished to do so, subject to the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be included in all
12
+ copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,46 @@
1
+ # react-native-local-download
2
+
3
+ Simple download folder access for react-native
4
+
5
+ Like my projects? Support me on ko-fi!
6
+
7
+ <a href='https://ko-fi.com/W7W7X8T7W' target='_blank'><img height='42' style='border:0px;height:42px;' src='https://storage.ko-fi.com/cdn/kofi6.png?v=6' border='0' alt='Buy Me a Coffee at ko-fi.com' /></a>
8
+
9
+ The purpose of this package is as an easy method to downloading.
10
+
11
+ - Uses MediaStorage for Android Download folder access
12
+ - Uses Sharing for iOS
13
+
14
+ This package is intended to be used with other file-system packages such as `expo-file-system` or `react-native-fs`
15
+
16
+ This was not tested on lower Android SDK API's, might not working on Android 9 and below.
17
+
18
+ ## Installation
19
+
20
+ ```sh
21
+ npm install @chatterui/react-native-local-download
22
+ ```
23
+
24
+ ## Usage
25
+
26
+ ```js
27
+ import { LocalDownload } from './NativeLocalDownload'
28
+
29
+ // Use simply add the path of the internal app resource to be copied to downloads
30
+ localDownload('/path/to/resource')
31
+
32
+ // Use a callback if you want to handle `never_ask_again` permissions on Android
33
+ localDownload('path/to/resource', () => console.log('Uh oh!'))
34
+ ```
35
+
36
+ ## Contributing
37
+
38
+ See the [contributing guide](CONTRIBUTING.md) to learn how to contribute to the repository and the development workflow.
39
+
40
+ ## License
41
+
42
+ MIT
43
+
44
+ ---
45
+
46
+ Made with [create-react-native-library](https://github.com/callstack/react-native-builder-bob)
@@ -0,0 +1,26 @@
1
+ require "json"
2
+
3
+ package = JSON.parse(File.read(File.join(__dir__, "package.json")))
4
+
5
+ Pod::Spec.new do |s|
6
+ s.name = "ReactNativeLocalDownload"
7
+ s.version = package["version"]
8
+ s.summary = package["description"]
9
+ s.homepage = package["homepage"]
10
+ s.license = package["license"]
11
+ s.authors = package["author"]
12
+
13
+ s.platforms = { :ios => min_ios_version_supported }
14
+ s.source = { :git => "https://github.com/Vali-98/chatterui-react-native-local-download.git", :tag => "#{s.version}" }
15
+
16
+ s.source_files = "ios/**/*.{h,m,mm,cpp}"
17
+ s.private_header_files = "ios/**/*.h"
18
+
19
+ # Use install_modules_dependencies helper to install the dependencies if React Native version >=0.71.0.
20
+ # See https://github.com/facebook/react-native/blob/febf6b7f33fdb4904669f99d795eba4c0f95d7bf/scripts/cocoapods/new_architecture.rb#L79.
21
+ if respond_to?(:install_modules_dependencies, true)
22
+ install_modules_dependencies(s)
23
+ else
24
+ s.dependency "React-Core"
25
+ end
26
+ end
@@ -0,0 +1,100 @@
1
+ buildscript {
2
+ ext.getExtOrDefault = {name ->
3
+ return rootProject.ext.has(name) ? rootProject.ext.get(name) : project.properties['ReactNativeLocalDownload_' + name]
4
+ }
5
+
6
+ repositories {
7
+ google()
8
+ mavenCentral()
9
+ }
10
+
11
+ dependencies {
12
+ classpath "com.android.tools.build:gradle:8.7.2"
13
+ // noinspection DifferentKotlinGradleVersion
14
+ classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:${getExtOrDefault('kotlinVersion')}"
15
+ }
16
+ }
17
+
18
+
19
+ apply plugin: "com.android.library"
20
+ apply plugin: "kotlin-android"
21
+
22
+ apply plugin: "com.facebook.react"
23
+
24
+ def getExtOrIntegerDefault(name) {
25
+ return rootProject.ext.has(name) ? rootProject.ext.get(name) : (project.properties["ReactNativeLocalDownload_" + name]).toInteger()
26
+ }
27
+
28
+ def supportsNamespace() {
29
+ def parsed = com.android.Version.ANDROID_GRADLE_PLUGIN_VERSION.tokenize('.')
30
+ def major = parsed[0].toInteger()
31
+ def minor = parsed[1].toInteger()
32
+
33
+ // Namespace support was added in 7.3.0
34
+ return (major == 7 && minor >= 3) || major >= 8
35
+ }
36
+
37
+ android {
38
+ if (supportsNamespace()) {
39
+ namespace "com.chatterui.reactnativelocaldownload"
40
+
41
+ sourceSets {
42
+ main {
43
+ manifest.srcFile "src/main/AndroidManifestNew.xml"
44
+ }
45
+ }
46
+ }
47
+
48
+ compileSdkVersion getExtOrIntegerDefault("compileSdkVersion")
49
+
50
+ defaultConfig {
51
+ minSdkVersion getExtOrIntegerDefault("minSdkVersion")
52
+ targetSdkVersion getExtOrIntegerDefault("targetSdkVersion")
53
+ }
54
+
55
+ buildFeatures {
56
+ buildConfig true
57
+ }
58
+
59
+ buildTypes {
60
+ release {
61
+ minifyEnabled false
62
+ }
63
+ }
64
+
65
+ lintOptions {
66
+ disable "GradleCompatible"
67
+ }
68
+
69
+ compileOptions {
70
+ sourceCompatibility JavaVersion.VERSION_1_8
71
+ targetCompatibility JavaVersion.VERSION_1_8
72
+ }
73
+
74
+ sourceSets {
75
+ main {
76
+ java.srcDirs += [
77
+ "generated/java",
78
+ "generated/jni"
79
+ ]
80
+ }
81
+ }
82
+ }
83
+
84
+ repositories {
85
+ mavenCentral()
86
+ google()
87
+ }
88
+
89
+ def kotlin_version = getExtOrDefault("kotlinVersion")
90
+
91
+ dependencies {
92
+ implementation "com.facebook.react:react-android"
93
+ implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
94
+ }
95
+
96
+ react {
97
+ jsRootDir = file("../src/")
98
+ libraryName = "ReactNativeLocalDownload"
99
+ codegenJavaPackageName = "com.chatterui.reactnativelocaldownload"
100
+ }
@@ -0,0 +1,38 @@
1
+
2
+ /**
3
+ * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen).
4
+ *
5
+ * Do not edit this file as changes may cause incorrect behavior and will be lost
6
+ * once the code is regenerated.
7
+ *
8
+ * @generated by codegen project: GenerateModuleJavaSpec.js
9
+ *
10
+ * @nolint
11
+ */
12
+
13
+ package com.chatterui.reactnativelocaldownload;
14
+
15
+ import com.facebook.proguard.annotations.DoNotStrip;
16
+ import com.facebook.react.bridge.Promise;
17
+ import com.facebook.react.bridge.ReactApplicationContext;
18
+ import com.facebook.react.bridge.ReactContextBaseJavaModule;
19
+ import com.facebook.react.bridge.ReactMethod;
20
+ import com.facebook.react.turbomodule.core.interfaces.TurboModule;
21
+ import javax.annotation.Nonnull;
22
+
23
+ public abstract class NativeReactNativeLocalDownloadSpec extends ReactContextBaseJavaModule implements TurboModule {
24
+ public static final String NAME = "ReactNativeLocalDownload";
25
+
26
+ public NativeReactNativeLocalDownloadSpec(ReactApplicationContext reactContext) {
27
+ super(reactContext);
28
+ }
29
+
30
+ @Override
31
+ public @Nonnull String getName() {
32
+ return NAME;
33
+ }
34
+
35
+ @ReactMethod
36
+ @DoNotStrip
37
+ public abstract void localDownload(String uri, Promise promise);
38
+ }
@@ -0,0 +1,36 @@
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ cmake_minimum_required(VERSION 3.13)
7
+ set(CMAKE_VERBOSE_MAKEFILE on)
8
+
9
+ file(GLOB react_codegen_SRCS CONFIGURE_DEPENDS *.cpp react/renderer/components/RNReactNativeLocalDownloadSpec/*.cpp)
10
+
11
+ add_library(
12
+ react_codegen_RNReactNativeLocalDownloadSpec
13
+ OBJECT
14
+ ${react_codegen_SRCS}
15
+ )
16
+
17
+ target_include_directories(react_codegen_RNReactNativeLocalDownloadSpec PUBLIC . react/renderer/components/RNReactNativeLocalDownloadSpec)
18
+
19
+ target_link_libraries(
20
+ react_codegen_RNReactNativeLocalDownloadSpec
21
+ fbjni
22
+ jsi
23
+ # We need to link different libraries based on whether we are building rncore or not, that's necessary
24
+ # because we want to break a circular dependency between react_codegen_rncore and reactnative
25
+ reactnative
26
+ )
27
+
28
+ target_compile_options(
29
+ react_codegen_RNReactNativeLocalDownloadSpec
30
+ PRIVATE
31
+ -DLOG_TAG=\"ReactNative\"
32
+ -fexceptions
33
+ -frtti
34
+ -std=c++20
35
+ -Wall
36
+ )
@@ -0,0 +1,32 @@
1
+
2
+ /**
3
+ * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen).
4
+ *
5
+ * Do not edit this file as changes may cause incorrect behavior and will be lost
6
+ * once the code is regenerated.
7
+ *
8
+ * @generated by codegen project: GenerateModuleJniCpp.js
9
+ */
10
+
11
+ #include "RNReactNativeLocalDownloadSpec.h"
12
+
13
+ namespace facebook::react {
14
+
15
+ static facebook::jsi::Value __hostFunction_NativeReactNativeLocalDownloadSpecJSI_localDownload(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) {
16
+ static jmethodID cachedMethodId = nullptr;
17
+ return static_cast<JavaTurboModule &>(turboModule).invokeJavaMethod(rt, PromiseKind, "localDownload", "(Ljava/lang/String;Lcom/facebook/react/bridge/Promise;)V", args, count, cachedMethodId);
18
+ }
19
+
20
+ NativeReactNativeLocalDownloadSpecJSI::NativeReactNativeLocalDownloadSpecJSI(const JavaTurboModule::InitParams &params)
21
+ : JavaTurboModule(params) {
22
+ methodMap_["localDownload"] = MethodMetadata {1, __hostFunction_NativeReactNativeLocalDownloadSpecJSI_localDownload};
23
+ }
24
+
25
+ std::shared_ptr<TurboModule> RNReactNativeLocalDownloadSpec_ModuleProvider(const std::string &moduleName, const JavaTurboModule::InitParams &params) {
26
+ if (moduleName == "ReactNativeLocalDownload") {
27
+ return std::make_shared<NativeReactNativeLocalDownloadSpecJSI>(params);
28
+ }
29
+ return nullptr;
30
+ }
31
+
32
+ } // namespace facebook::react
@@ -0,0 +1,31 @@
1
+
2
+ /**
3
+ * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen).
4
+ *
5
+ * Do not edit this file as changes may cause incorrect behavior and will be lost
6
+ * once the code is regenerated.
7
+ *
8
+ * @generated by codegen project: GenerateModuleJniH.js
9
+ */
10
+
11
+ #pragma once
12
+
13
+ #include <ReactCommon/JavaTurboModule.h>
14
+ #include <ReactCommon/TurboModule.h>
15
+ #include <jsi/jsi.h>
16
+
17
+ namespace facebook::react {
18
+
19
+ /**
20
+ * JNI C++ class for module 'NativeReactNativeLocalDownload'
21
+ */
22
+ class JSI_EXPORT NativeReactNativeLocalDownloadSpecJSI : public JavaTurboModule {
23
+ public:
24
+ NativeReactNativeLocalDownloadSpecJSI(const JavaTurboModule::InitParams &params);
25
+ };
26
+
27
+
28
+ JSI_EXPORT
29
+ std::shared_ptr<TurboModule> RNReactNativeLocalDownloadSpec_ModuleProvider(const std::string &moduleName, const JavaTurboModule::InitParams &params);
30
+
31
+ } // namespace facebook::react
@@ -0,0 +1,27 @@
1
+ /**
2
+ * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen).
3
+ *
4
+ * Do not edit this file as changes may cause incorrect behavior and will be lost
5
+ * once the code is regenerated.
6
+ *
7
+ * @generated by codegen project: GenerateModuleCpp.js
8
+ */
9
+
10
+ #include "RNReactNativeLocalDownloadSpecJSI.h"
11
+
12
+ namespace facebook::react {
13
+
14
+ static jsi::Value __hostFunction_NativeReactNativeLocalDownloadCxxSpecJSI_localDownload(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) {
15
+ return static_cast<NativeReactNativeLocalDownloadCxxSpecJSI *>(&turboModule)->localDownload(
16
+ rt,
17
+ count <= 0 ? throw jsi::JSError(rt, "Expected argument in position 0 to be passed") : args[0].asString(rt)
18
+ );
19
+ }
20
+
21
+ NativeReactNativeLocalDownloadCxxSpecJSI::NativeReactNativeLocalDownloadCxxSpecJSI(std::shared_ptr<CallInvoker> jsInvoker)
22
+ : TurboModule("ReactNativeLocalDownload", jsInvoker) {
23
+ methodMap_["localDownload"] = MethodMetadata {1, __hostFunction_NativeReactNativeLocalDownloadCxxSpecJSI_localDownload};
24
+ }
25
+
26
+
27
+ } // namespace facebook::react
@@ -0,0 +1,71 @@
1
+ /**
2
+ * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen).
3
+ *
4
+ * Do not edit this file as changes may cause incorrect behavior and will be lost
5
+ * once the code is regenerated.
6
+ *
7
+ * @generated by codegen project: GenerateModuleH.js
8
+ */
9
+
10
+ #pragma once
11
+
12
+ #include <ReactCommon/TurboModule.h>
13
+ #include <react/bridging/Bridging.h>
14
+
15
+ namespace facebook::react {
16
+
17
+
18
+ class JSI_EXPORT NativeReactNativeLocalDownloadCxxSpecJSI : public TurboModule {
19
+ protected:
20
+ NativeReactNativeLocalDownloadCxxSpecJSI(std::shared_ptr<CallInvoker> jsInvoker);
21
+
22
+ public:
23
+ virtual jsi::Value localDownload(jsi::Runtime &rt, jsi::String uri) = 0;
24
+
25
+ };
26
+
27
+ template <typename T>
28
+ class JSI_EXPORT NativeReactNativeLocalDownloadCxxSpec : public TurboModule {
29
+ public:
30
+ jsi::Value create(jsi::Runtime &rt, const jsi::PropNameID &propName) override {
31
+ return delegate_.create(rt, propName);
32
+ }
33
+
34
+ std::vector<jsi::PropNameID> getPropertyNames(jsi::Runtime& runtime) override {
35
+ return delegate_.getPropertyNames(runtime);
36
+ }
37
+
38
+ static constexpr std::string_view kModuleName = "ReactNativeLocalDownload";
39
+
40
+ protected:
41
+ NativeReactNativeLocalDownloadCxxSpec(std::shared_ptr<CallInvoker> jsInvoker)
42
+ : TurboModule(std::string{NativeReactNativeLocalDownloadCxxSpec::kModuleName}, jsInvoker),
43
+ delegate_(reinterpret_cast<T*>(this), jsInvoker) {}
44
+
45
+
46
+ private:
47
+ class Delegate : public NativeReactNativeLocalDownloadCxxSpecJSI {
48
+ public:
49
+ Delegate(T *instance, std::shared_ptr<CallInvoker> jsInvoker) :
50
+ NativeReactNativeLocalDownloadCxxSpecJSI(std::move(jsInvoker)), instance_(instance) {
51
+
52
+ }
53
+
54
+ jsi::Value localDownload(jsi::Runtime &rt, jsi::String uri) override {
55
+ static_assert(
56
+ bridging::getParameterCount(&T::localDownload) == 2,
57
+ "Expected localDownload(...) to have 2 parameters");
58
+
59
+ return bridging::callFromJs<jsi::Value>(
60
+ rt, &T::localDownload, jsInvoker_, instance_, std::move(uri));
61
+ }
62
+
63
+ private:
64
+ friend class NativeReactNativeLocalDownloadCxxSpec;
65
+ T *instance_;
66
+ };
67
+
68
+ Delegate delegate_;
69
+ };
70
+
71
+ } // namespace facebook::react
@@ -0,0 +1,5 @@
1
+ ReactNativeLocalDownload_kotlinVersion=2.0.21
2
+ ReactNativeLocalDownload_minSdkVersion=24
3
+ ReactNativeLocalDownload_targetSdkVersion=34
4
+ ReactNativeLocalDownload_compileSdkVersion=35
5
+ ReactNativeLocalDownload_ndkVersion=27.1.12297006
@@ -0,0 +1,5 @@
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android"
2
+ package="com.chatterui.reactnativelocaldownload">
3
+ <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
4
+ android:maxSdkVersion="28" />
5
+ </manifest>
@@ -0,0 +1,2 @@
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android">
2
+ </manifest>
@@ -0,0 +1,95 @@
1
+ package com.chatterui.reactnativelocaldownload
2
+
3
+ import com.facebook.react.bridge.ReactApplicationContext
4
+ import com.facebook.react.bridge.Promise
5
+ import com.facebook.react.module.annotations.ReactModule
6
+
7
+ import android.content.ContentValues
8
+ import android.content.ContentResolver
9
+ import android.net.Uri
10
+ import android.provider.MediaStore
11
+ import java.io.File
12
+ import java.io.FileInputStream
13
+ import java.io.FileOutputStream
14
+ import java.net.URLConnection
15
+
16
+ @ReactModule(name = ReactNativeLocalDownloadModule.NAME)
17
+ class ReactNativeLocalDownloadModule(private val reactContext: ReactApplicationContext) :
18
+ NativeReactNativeLocalDownloadSpec(reactContext) {
19
+
20
+ override fun getName(): String {
21
+ return NAME
22
+ }
23
+
24
+ override fun localDownload(uri: String, promise: Promise) {
25
+ try {
26
+ val inputFile = File(uri)
27
+ if (!inputFile.exists()) {
28
+ promise.reject("FILE_NOT_FOUND", "File does not exist at path: $uri")
29
+ return
30
+ }
31
+
32
+ val fileName = inputFile.name
33
+ val mimeType = URLConnection.guessContentTypeFromName(inputFile.name) ?: "application/octet-stream"
34
+ val resolver : ContentResolver = reactContext.contentResolver
35
+ val uniqueName = getUniqueFileName(resolver, fileName)
36
+ val contentValues = ContentValues().apply {
37
+ put(MediaStore.Downloads.DISPLAY_NAME, uniqueName)
38
+ put(MediaStore.Downloads.MIME_TYPE, mimeType)
39
+ put(MediaStore.Downloads.IS_PENDING, 1)
40
+ }
41
+
42
+ val collection = MediaStore.Downloads.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
43
+ val itemUri = resolver.insert(collection, contentValues)
44
+
45
+ if (itemUri == null) {
46
+ promise.reject("SAVE_ERROR", "Failed to create destination file in MediaStore.")
47
+ return
48
+ }
49
+
50
+ resolver.openOutputStream(itemUri)?.use { outputStream ->
51
+ inputFile.inputStream().use { inputStream ->
52
+ inputStream.copyTo(outputStream)
53
+ }
54
+ }
55
+
56
+ // Mark the item as not pending so it's visible to user
57
+ contentValues.clear()
58
+ contentValues.put(MediaStore.Downloads.IS_PENDING, 0)
59
+ resolver.update(itemUri, contentValues, null, null)
60
+
61
+ promise.resolve(itemUri.toString())
62
+ } catch (e: Exception) {
63
+ promise.reject("DOWNLOAD_ERROR", "Failed to save file via MediaStore: ${e.message}", e)
64
+ }
65
+ }
66
+
67
+ private fun getUniqueFileName(resolver: ContentResolver, baseName: String): String {
68
+ var name = baseName
69
+ val nameWithoutExtension = File(baseName).nameWithoutExtension
70
+ val extension = File(baseName).extension
71
+ var index = 1
72
+
73
+ val collection = MediaStore.Downloads.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
74
+
75
+ val projection = arrayOf(MediaStore.Downloads.DISPLAY_NAME)
76
+ val selection = "${MediaStore.Downloads.DISPLAY_NAME} = ?"
77
+ val selectionArgs = arrayOf(name)
78
+
79
+ while (resolver.query(collection, projection, selection, selectionArgs, null)?.use { it.moveToFirst() } == true) {
80
+ name = if (extension.isNotEmpty()) {
81
+ "$nameWithoutExtension ($index).$extension"
82
+ } else {
83
+ "$nameWithoutExtension ($index)"
84
+ }
85
+ selectionArgs[0] = name
86
+ index++
87
+ }
88
+
89
+ return name
90
+ }
91
+
92
+ companion object {
93
+ const val NAME = "ReactNativeLocalDownload"
94
+ }
95
+ }
@@ -0,0 +1,33 @@
1
+ package com.chatterui.reactnativelocaldownload
2
+
3
+ import com.facebook.react.BaseReactPackage
4
+ import com.facebook.react.bridge.NativeModule
5
+ import com.facebook.react.bridge.ReactApplicationContext
6
+ import com.facebook.react.module.model.ReactModuleInfo
7
+ import com.facebook.react.module.model.ReactModuleInfoProvider
8
+ import java.util.HashMap
9
+
10
+ class ReactNativeLocalDownloadPackage : BaseReactPackage() {
11
+ override fun getModule(name: String, reactContext: ReactApplicationContext): NativeModule? {
12
+ return if (name == ReactNativeLocalDownloadModule.NAME) {
13
+ ReactNativeLocalDownloadModule(reactContext)
14
+ } else {
15
+ null
16
+ }
17
+ }
18
+
19
+ override fun getReactModuleInfoProvider(): ReactModuleInfoProvider {
20
+ return ReactModuleInfoProvider {
21
+ val moduleInfos: MutableMap<String, ReactModuleInfo> = HashMap()
22
+ moduleInfos[ReactNativeLocalDownloadModule.NAME] = ReactModuleInfo(
23
+ ReactNativeLocalDownloadModule.NAME,
24
+ ReactNativeLocalDownloadModule.NAME,
25
+ false, // canOverrideExistingModule
26
+ false, // needsEagerInit
27
+ false, // isCxxModule
28
+ true // isTurboModule
29
+ )
30
+ moduleInfos
31
+ }
32
+ }
33
+ }
@@ -0,0 +1,6 @@
1
+
2
+ #import <ReactNativeLocalDownload/RNReactNativeLocalDownloadSpec.h>
3
+
4
+ @interface ReactNativeLocalDownload : NSObject <NativeReactNativeLocalDownloadSpec>
5
+
6
+ @end
@@ -0,0 +1,35 @@
1
+ #import "ReactNativeLocalDownload.h"
2
+ #import <UIKit/UIKit.h>
3
+
4
+ @implementation ReactNativeLocalDownload
5
+ RCT_EXPORT_MODULE()
6
+
7
+ - (void)localDownload:(NSString *)uri
8
+ resolve:(RCTPromiseResolveBlock)resolve
9
+ reject:(RCTPromiseRejectBlock)reject
10
+ {
11
+ dispatch_async(dispatch_get_main_queue(), ^{
12
+ NSURL *fileURL = [NSURL fileURLWithPath:uri];
13
+ if (![fileURL isFileURL] || ![[NSFileManager defaultManager] fileExistsAtPath:uri]) {
14
+ reject(@"invalid_file", @"The file URI is not valid or the file does not exist", nil);
15
+ return;
16
+ }
17
+
18
+ UIActivityViewController *controller = [[UIActivityViewController alloc]
19
+ initWithActivityItems:@[fileURL]
20
+ applicationActivities:nil];
21
+
22
+ UIViewController *rootVC = UIApplication.sharedApplication.delegate.window.rootViewController;
23
+ [rootVC presentViewController:controller animated:YES completion:nil];
24
+
25
+ resolve(nil);
26
+ });
27
+ }
28
+
29
+ - (std::shared_ptr<facebook::react::TurboModule>)getTurboModule:
30
+ (const facebook::react::ObjCTurboModule::InitParams &)params
31
+ {
32
+ return std::make_shared<facebook::react::NativeReactNativeLocalDownloadSpecJSI>(params);
33
+ }
34
+
35
+ @end
@@ -0,0 +1,39 @@
1
+ /**
2
+ * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen).
3
+ *
4
+ * Do not edit this file as changes may cause incorrect behavior and will be lost
5
+ * once the code is regenerated.
6
+ *
7
+ * @generated by codegen project: GenerateModuleObjCpp
8
+ *
9
+ * We create an umbrella header (and corresponding implementation) here since
10
+ * Cxx compilation in BUCK has a limitation: source-code producing genrule()s
11
+ * must have a single output. More files => more genrule()s => slower builds.
12
+ */
13
+
14
+ #import "RNReactNativeLocalDownloadSpec.h"
15
+
16
+
17
+ @implementation NativeReactNativeLocalDownloadSpecBase
18
+
19
+
20
+ - (void)setEventEmitterCallback:(EventEmitterCallbackWrapper *)eventEmitterCallbackWrapper
21
+ {
22
+ _eventEmitterCallback = std::move(eventEmitterCallbackWrapper->_eventEmitterCallback);
23
+ }
24
+ @end
25
+
26
+
27
+ namespace facebook::react {
28
+
29
+ static facebook::jsi::Value __hostFunction_NativeReactNativeLocalDownloadSpecJSI_localDownload(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) {
30
+ return static_cast<ObjCTurboModule&>(turboModule).invokeObjCMethod(rt, PromiseKind, "localDownload", @selector(localDownload:resolve:reject:), args, count);
31
+ }
32
+
33
+ NativeReactNativeLocalDownloadSpecJSI::NativeReactNativeLocalDownloadSpecJSI(const ObjCTurboModule::InitParams &params)
34
+ : ObjCTurboModule(params) {
35
+
36
+ methodMap_["localDownload"] = MethodMetadata {1, __hostFunction_NativeReactNativeLocalDownloadSpecJSI_localDownload};
37
+
38
+ }
39
+ } // namespace facebook::react
@@ -0,0 +1,64 @@
1
+ /**
2
+ * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen).
3
+ *
4
+ * Do not edit this file as changes may cause incorrect behavior and will be lost
5
+ * once the code is regenerated.
6
+ *
7
+ * @generated by codegen project: GenerateModuleObjCpp
8
+ *
9
+ * We create an umbrella header (and corresponding implementation) here since
10
+ * Cxx compilation in BUCK has a limitation: source-code producing genrule()s
11
+ * must have a single output. More files => more genrule()s => slower builds.
12
+ */
13
+
14
+ #ifndef __cplusplus
15
+ #error This file must be compiled as Obj-C++. If you are importing it, you must change your file extension to .mm.
16
+ #endif
17
+
18
+ // Avoid multiple includes of RNReactNativeLocalDownloadSpec symbols
19
+ #ifndef RNReactNativeLocalDownloadSpec_H
20
+ #define RNReactNativeLocalDownloadSpec_H
21
+
22
+ #import <Foundation/Foundation.h>
23
+ #import <RCTRequired/RCTRequired.h>
24
+ #import <RCTTypeSafety/RCTConvertHelpers.h>
25
+ #import <RCTTypeSafety/RCTTypedModuleConstants.h>
26
+ #import <React/RCTBridgeModule.h>
27
+ #import <React/RCTCxxConvert.h>
28
+ #import <React/RCTManagedPointer.h>
29
+ #import <ReactCommon/RCTTurboModule.h>
30
+ #import <optional>
31
+ #import <vector>
32
+
33
+
34
+ NS_ASSUME_NONNULL_BEGIN
35
+
36
+ @protocol NativeReactNativeLocalDownloadSpec <RCTBridgeModule, RCTTurboModule>
37
+
38
+ - (void)localDownload:(NSString *)uri
39
+ resolve:(RCTPromiseResolveBlock)resolve
40
+ reject:(RCTPromiseRejectBlock)reject;
41
+
42
+ @end
43
+
44
+ @interface NativeReactNativeLocalDownloadSpecBase : NSObject {
45
+ @protected
46
+ facebook::react::EventEmitterCallback _eventEmitterCallback;
47
+ }
48
+ - (void)setEventEmitterCallback:(EventEmitterCallbackWrapper *)eventEmitterCallbackWrapper;
49
+
50
+
51
+ @end
52
+
53
+ namespace facebook::react {
54
+ /**
55
+ * ObjC++ class for module 'NativeReactNativeLocalDownload'
56
+ */
57
+ class JSI_EXPORT NativeReactNativeLocalDownloadSpecJSI : public ObjCTurboModule {
58
+ public:
59
+ NativeReactNativeLocalDownloadSpecJSI(const ObjCTurboModule::InitParams &params);
60
+ };
61
+ } // namespace facebook::react
62
+
63
+ NS_ASSUME_NONNULL_END
64
+ #endif // RNReactNativeLocalDownloadSpec_H
@@ -0,0 +1,27 @@
1
+ /**
2
+ * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen).
3
+ *
4
+ * Do not edit this file as changes may cause incorrect behavior and will be lost
5
+ * once the code is regenerated.
6
+ *
7
+ * @generated by codegen project: GenerateModuleCpp.js
8
+ */
9
+
10
+ #include "RNReactNativeLocalDownloadSpecJSI.h"
11
+
12
+ namespace facebook::react {
13
+
14
+ static jsi::Value __hostFunction_NativeReactNativeLocalDownloadCxxSpecJSI_localDownload(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) {
15
+ return static_cast<NativeReactNativeLocalDownloadCxxSpecJSI *>(&turboModule)->localDownload(
16
+ rt,
17
+ count <= 0 ? throw jsi::JSError(rt, "Expected argument in position 0 to be passed") : args[0].asString(rt)
18
+ );
19
+ }
20
+
21
+ NativeReactNativeLocalDownloadCxxSpecJSI::NativeReactNativeLocalDownloadCxxSpecJSI(std::shared_ptr<CallInvoker> jsInvoker)
22
+ : TurboModule("ReactNativeLocalDownload", jsInvoker) {
23
+ methodMap_["localDownload"] = MethodMetadata {1, __hostFunction_NativeReactNativeLocalDownloadCxxSpecJSI_localDownload};
24
+ }
25
+
26
+
27
+ } // namespace facebook::react
@@ -0,0 +1,71 @@
1
+ /**
2
+ * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen).
3
+ *
4
+ * Do not edit this file as changes may cause incorrect behavior and will be lost
5
+ * once the code is regenerated.
6
+ *
7
+ * @generated by codegen project: GenerateModuleH.js
8
+ */
9
+
10
+ #pragma once
11
+
12
+ #include <ReactCommon/TurboModule.h>
13
+ #include <react/bridging/Bridging.h>
14
+
15
+ namespace facebook::react {
16
+
17
+
18
+ class JSI_EXPORT NativeReactNativeLocalDownloadCxxSpecJSI : public TurboModule {
19
+ protected:
20
+ NativeReactNativeLocalDownloadCxxSpecJSI(std::shared_ptr<CallInvoker> jsInvoker);
21
+
22
+ public:
23
+ virtual jsi::Value localDownload(jsi::Runtime &rt, jsi::String uri) = 0;
24
+
25
+ };
26
+
27
+ template <typename T>
28
+ class JSI_EXPORT NativeReactNativeLocalDownloadCxxSpec : public TurboModule {
29
+ public:
30
+ jsi::Value create(jsi::Runtime &rt, const jsi::PropNameID &propName) override {
31
+ return delegate_.create(rt, propName);
32
+ }
33
+
34
+ std::vector<jsi::PropNameID> getPropertyNames(jsi::Runtime& runtime) override {
35
+ return delegate_.getPropertyNames(runtime);
36
+ }
37
+
38
+ static constexpr std::string_view kModuleName = "ReactNativeLocalDownload";
39
+
40
+ protected:
41
+ NativeReactNativeLocalDownloadCxxSpec(std::shared_ptr<CallInvoker> jsInvoker)
42
+ : TurboModule(std::string{NativeReactNativeLocalDownloadCxxSpec::kModuleName}, jsInvoker),
43
+ delegate_(reinterpret_cast<T*>(this), jsInvoker) {}
44
+
45
+
46
+ private:
47
+ class Delegate : public NativeReactNativeLocalDownloadCxxSpecJSI {
48
+ public:
49
+ Delegate(T *instance, std::shared_ptr<CallInvoker> jsInvoker) :
50
+ NativeReactNativeLocalDownloadCxxSpecJSI(std::move(jsInvoker)), instance_(instance) {
51
+
52
+ }
53
+
54
+ jsi::Value localDownload(jsi::Runtime &rt, jsi::String uri) override {
55
+ static_assert(
56
+ bridging::getParameterCount(&T::localDownload) == 2,
57
+ "Expected localDownload(...) to have 2 parameters");
58
+
59
+ return bridging::callFromJs<jsi::Value>(
60
+ rt, &T::localDownload, jsInvoker_, instance_, std::move(uri));
61
+ }
62
+
63
+ private:
64
+ friend class NativeReactNativeLocalDownloadCxxSpec;
65
+ T *instance_;
66
+ };
67
+
68
+ Delegate delegate_;
69
+ };
70
+
71
+ } // namespace facebook::react
@@ -0,0 +1,8 @@
1
+ import type { TurboModule } from 'react-native';
2
+ import { TurboModuleRegistry } from 'react-native';
3
+
4
+ export interface Spec extends TurboModule {
5
+ localDownload(uri: string): Promise<void>
6
+ }
7
+
8
+ export default TurboModuleRegistry.getEnforcing<Spec>('ReactNativeLocalDownload');
@@ -0,0 +1,48 @@
1
+ "use strict";
2
+
3
+ import ReactNativeLocalDownload from './NativeReactNativeLocalDownload';
4
+ import { PermissionsAndroid, Platform, Linking, Alert } from 'react-native';
5
+ /**
6
+ *
7
+ * @param uri path to content to be sent to downloads
8
+ * @param never_ask_function callback if android permissions are set to `never_ask_again`
9
+ * @returns
10
+ */
11
+ export async function localDownload(uri, never_ask_function) {
12
+ const granted = await requestStoragePermission();
13
+ if (granted !== 'granted') {
14
+ if (granted === PermissionsAndroid.RESULTS.NEVER_ASK_AGAIN) {
15
+ if (!never_ask_function) Alert.alert('Permission Required', 'You have permanently denied storage access. Please enable it from settings.', [{
16
+ text: 'Cancel',
17
+ style: 'cancel'
18
+ }, {
19
+ text: 'Open Settings',
20
+ onPress: () => Linking.openSettings()
21
+ }]);else never_ask_function();
22
+ }
23
+ throw new Error('Permissions not granted');
24
+ }
25
+ return ReactNativeLocalDownload.localDownload(uri);
26
+ }
27
+ export const requestStoragePermission = async () => {
28
+ if (Platform.OS !== 'android') return PermissionsAndroid.RESULTS.GRANTED;
29
+ try {
30
+ if (Number(Platform.Version) >= 33) {
31
+ return 'granted';
32
+ }
33
+ const hasPermission = await PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE);
34
+ if (hasPermission) {
35
+ return 'granted';
36
+ }
37
+ const granted = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE, {
38
+ title: 'Storage Permission',
39
+ message: 'This app needs access to your storage to download files.',
40
+ buttonPositive: 'OK'
41
+ });
42
+ return granted;
43
+ } catch (err) {
44
+ console.warn(err);
45
+ return PermissionsAndroid.RESULTS.DENIED;
46
+ }
47
+ };
48
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"names":["ReactNativeLocalDownload","PermissionsAndroid","Platform","Linking","Alert","localDownload","uri","never_ask_function","granted","requestStoragePermission","RESULTS","NEVER_ASK_AGAIN","alert","text","style","onPress","openSettings","Error","OS","GRANTED","Number","Version","hasPermission","check","PERMISSIONS","WRITE_EXTERNAL_STORAGE","request","title","message","buttonPositive","err","console","warn","DENIED"],"sourceRoot":"../../src","sources":["index.tsx"],"mappings":";;AAAA,OAAOA,wBAAwB,MAAM,kCAAkC;AAEvE,SAASC,kBAAkB,EAAEC,QAAQ,EAAEC,OAAO,EAAEC,KAAK,QAAQ,cAAc;AAC3E;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,eAAeC,aAAaA,CAC/BC,GAAW,EACXC,kBAA2C,EAC9B;EACb,MAAMC,OAAO,GAAG,MAAMC,wBAAwB,CAAC,CAAC;EAChD,IAAID,OAAO,KAAK,SAAS,EAAE;IACvB,IAAIA,OAAO,KAAKP,kBAAkB,CAACS,OAAO,CAACC,eAAe,EAAE;MACxD,IAAI,CAACJ,kBAAkB,EACnBH,KAAK,CAACQ,KAAK,CACP,qBAAqB,EACrB,6EAA6E,EAC7E,CACI;QAAEC,IAAI,EAAE,QAAQ;QAAEC,KAAK,EAAE;MAAS,CAAC,EACnC;QAAED,IAAI,EAAE,eAAe;QAAEE,OAAO,EAAEA,CAAA,KAAMZ,OAAO,CAACa,YAAY,CAAC;MAAE,CAAC,CAExE,CAAC,MACAT,kBAAkB,CAAC,CAAC;IAC7B;IACA,MAAM,IAAIU,KAAK,CAAC,yBAAyB,CAAC;EAC9C;EACA,OAAOjB,wBAAwB,CAACK,aAAa,CAACC,GAAG,CAAC;AACtD;AAEA,OAAO,MAAMG,wBAAwB,GAAG,MAAAA,CAAA,KAEnC;EACD,IAAIP,QAAQ,CAACgB,EAAE,KAAK,SAAS,EAAE,OAAOjB,kBAAkB,CAACS,OAAO,CAACS,OAAO;EAExE,IAAI;IACA,IAAIC,MAAM,CAAClB,QAAQ,CAACmB,OAAO,CAAC,IAAI,EAAE,EAAE;MAChC,OAAO,SAAS;IACpB;IAEA,MAAMC,aAAa,GAAG,MAAMrB,kBAAkB,CAACsB,KAAK,CAChDtB,kBAAkB,CAACuB,WAAW,CAACC,sBACnC,CAAC;IACD,IAAIH,aAAa,EAAE;MACf,OAAO,SAAS;IACpB;IAEA,MAAMd,OAAO,GAAG,MAAMP,kBAAkB,CAACyB,OAAO,CAC5CzB,kBAAkB,CAACuB,WAAW,CAACC,sBAAsB,EACrD;MACIE,KAAK,EAAE,oBAAoB;MAC3BC,OAAO,EAAE,0DAA0D;MACnEC,cAAc,EAAE;IACpB,CACJ,CAAC;IACD,OAAOrB,OAAO;EAClB,CAAC,CAAC,OAAOsB,GAAG,EAAE;IACVC,OAAO,CAACC,IAAI,CAACF,GAAG,CAAC;IACjB,OAAO7B,kBAAkB,CAACS,OAAO,CAACuB,MAAM;EAC5C;AACJ,CAAC","ignoreList":[]}
@@ -0,0 +1 @@
1
+ {"type":"module"}
@@ -0,0 +1 @@
1
+ {"type":"module"}
@@ -0,0 +1,7 @@
1
+ import type { TurboModule } from 'react-native';
2
+ export interface Spec extends TurboModule {
3
+ localDownload(uri: string): Promise<void>;
4
+ }
5
+ declare const _default: Spec;
6
+ export default _default;
7
+ //# sourceMappingURL=NativeReactNativeLocalDownload.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"NativeReactNativeLocalDownload.d.ts","sourceRoot":"","sources":["../../../src/NativeReactNativeLocalDownload.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAGhD,MAAM,WAAW,IAAK,SAAQ,WAAW;IACvC,aAAa,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;CAC1C;;AAED,wBAAkF"}
@@ -0,0 +1,10 @@
1
+ import { PermissionsAndroid } from 'react-native';
2
+ /**
3
+ *
4
+ * @param uri path to content to be sent to downloads
5
+ * @param never_ask_function callback if android permissions are set to `never_ask_again`
6
+ * @returns
7
+ */
8
+ export declare function localDownload(uri: string, never_ask_function?: () => void | undefined): Promise<void>;
9
+ export declare const requestStoragePermission: () => Promise<typeof PermissionsAndroid.RESULTS.DENIED>;
10
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/index.tsx"],"names":[],"mappings":"AAEA,OAAO,EAAE,kBAAkB,EAA4B,MAAM,cAAc,CAAA;AAC3E;;;;;GAKG;AACH,wBAAsB,aAAa,CAC/B,GAAG,EAAE,MAAM,EACX,kBAAkB,CAAC,EAAE,MAAM,IAAI,GAAG,SAAS,GAC5C,OAAO,CAAC,IAAI,CAAC,CAkBf;AAED,eAAO,MAAM,wBAAwB,QAAa,OAAO,CACrD,OAAO,kBAAkB,CAAC,OAAO,CAAC,MAAM,CA6B3C,CAAA"}
package/package.json ADDED
@@ -0,0 +1,170 @@
1
+ {
2
+ "name": "@vali98/react-native-fs",
3
+ "version": "0.1.0",
4
+ "description": "Download folder access for react-native",
5
+ "source": "./src/index.tsx",
6
+ "main": "./lib/module/index.js",
7
+ "types": "./lib/typescript/src/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./lib/typescript/src/index.d.ts",
11
+ "default": "./lib/module/index.js"
12
+ },
13
+ "./package.json": "./package.json"
14
+ },
15
+ "files": [
16
+ "src",
17
+ "lib",
18
+ "android",
19
+ "ios",
20
+ "cpp",
21
+ "*.podspec",
22
+ "react-native.config.js",
23
+ "!ios/build",
24
+ "!android/build",
25
+ "!android/gradle",
26
+ "!android/gradlew",
27
+ "!android/gradlew.bat",
28
+ "!android/local.properties",
29
+ "!**/__tests__",
30
+ "!**/__fixtures__",
31
+ "!**/__mocks__",
32
+ "!**/.*"
33
+ ],
34
+ "scripts": {
35
+ "example": "yarn workspace @chatterui/react-native-local-download-example",
36
+ "test": "jest",
37
+ "typecheck": "tsc",
38
+ "lint": "eslint \"**/*.{js,ts,tsx}\"",
39
+ "clean": "del-cli android/build example/android/build example/android/app/build example/ios/build lib",
40
+ "prepare": "bob build",
41
+ "release": "release-it"
42
+ },
43
+ "keywords": [
44
+ "react-native",
45
+ "ios",
46
+ "android"
47
+ ],
48
+ "repository": {
49
+ "type": "git",
50
+ "url": "git+https://github.com/Vali-98/chatterui-react-native-local-download.git"
51
+ },
52
+ "author": "Vali98 <al244098@gmail.com> (https://github.com/Vali-98)",
53
+ "license": "MIT",
54
+ "bugs": {
55
+ "url": "https://github.com/Vali-98/chatterui-react-native-local-download/issues"
56
+ },
57
+ "homepage": "https://github.com/Vali-98/chatterui-react-native-local-download#readme",
58
+ "publishConfig": {
59
+ "registry": "https://registry.npmjs.org/",
60
+ "access": "public"
61
+ },
62
+ "devDependencies": {
63
+ "@commitlint/config-conventional": "^19.6.0",
64
+ "@eslint/compat": "^1.2.7",
65
+ "@eslint/eslintrc": "^3.3.0",
66
+ "@eslint/js": "^9.22.0",
67
+ "@evilmartians/lefthook": "^1.5.0",
68
+ "@react-native-community/cli": "15.0.1",
69
+ "@react-native/eslint-config": "^0.78.0",
70
+ "@release-it/conventional-changelog": "^9.0.2",
71
+ "@types/jest": "^29.5.5",
72
+ "@types/react": "^19.0.0",
73
+ "commitlint": "^19.6.1",
74
+ "del-cli": "^5.1.0",
75
+ "eslint": "^9.22.0",
76
+ "eslint-config-prettier": "^10.1.1",
77
+ "eslint-plugin-prettier": "^5.2.3",
78
+ "jest": "^29.7.0",
79
+ "prettier": "^3.0.3",
80
+ "react": "19.0.0",
81
+ "react-native": "0.78.2",
82
+ "react-native-builder-bob": "^0.40.6",
83
+ "release-it": "^17.10.0",
84
+ "turbo": "^1.10.7",
85
+ "typescript": "^5.2.2"
86
+ },
87
+ "peerDependencies": {
88
+ "react": "*",
89
+ "react-native": "*"
90
+ },
91
+ "workspaces": [
92
+ "example"
93
+ ],
94
+ "packageManager": "yarn@3.6.1",
95
+ "jest": {
96
+ "preset": "react-native",
97
+ "modulePathIgnorePatterns": [
98
+ "<rootDir>/example/node_modules",
99
+ "<rootDir>/lib/"
100
+ ]
101
+ },
102
+ "commitlint": {
103
+ "extends": [
104
+ "@commitlint/config-conventional"
105
+ ]
106
+ },
107
+ "release-it": {
108
+ "git": {
109
+ "commitMessage": "chore: release ${version}",
110
+ "tagName": "v${version}"
111
+ },
112
+ "npm": {
113
+ "publish": true
114
+ },
115
+ "github": {
116
+ "release": true
117
+ },
118
+ "plugins": {
119
+ "@release-it/conventional-changelog": {
120
+ "preset": {
121
+ "name": "angular"
122
+ }
123
+ }
124
+ }
125
+ },
126
+ "prettier": {
127
+ "quoteProps": "consistent",
128
+ "singleQuote": true,
129
+ "tabWidth": 2,
130
+ "trailingComma": "es5",
131
+ "useTabs": false
132
+ },
133
+ "react-native-builder-bob": {
134
+ "source": "src",
135
+ "output": "lib",
136
+ "targets": [
137
+ "codegen",
138
+ [
139
+ "module",
140
+ {
141
+ "esm": true
142
+ }
143
+ ],
144
+ [
145
+ "typescript",
146
+ {
147
+ "project": "tsconfig.build.json"
148
+ }
149
+ ]
150
+ ]
151
+ },
152
+ "codegenConfig": {
153
+ "name": "RNReactNativeLocalDownloadSpec",
154
+ "type": "modules",
155
+ "jsSrcsDir": "src",
156
+ "outputDir": {
157
+ "ios": "ios/generated",
158
+ "android": "android/generated"
159
+ },
160
+ "android": {
161
+ "javaPackageName": "com.chatterui.reactnativelocaldownload"
162
+ },
163
+ "includesGeneratedCode": true
164
+ },
165
+ "create-react-native-library": {
166
+ "type": "turbo-module",
167
+ "languages": "kotlin-objc",
168
+ "version": "0.49.8"
169
+ }
170
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * @type {import('@react-native-community/cli-types').UserDependencyConfig}
3
+ */
4
+ module.exports = {
5
+ dependency: {
6
+ platforms: {
7
+ android: {
8
+ cmakeListsPath: 'generated/jni/CMakeLists.txt',
9
+ },
10
+ },
11
+ },
12
+ };
@@ -0,0 +1,8 @@
1
+ import type { TurboModule } from 'react-native';
2
+ import { TurboModuleRegistry } from 'react-native';
3
+
4
+ export interface Spec extends TurboModule {
5
+ localDownload(uri: string): Promise<void>
6
+ }
7
+
8
+ export default TurboModuleRegistry.getEnforcing<Spec>('ReactNativeLocalDownload');
package/src/index.tsx ADDED
@@ -0,0 +1,64 @@
1
+ import ReactNativeLocalDownload from './NativeReactNativeLocalDownload';
2
+
3
+ import { PermissionsAndroid, Platform, Linking, Alert } from 'react-native'
4
+ /**
5
+ *
6
+ * @param uri path to content to be sent to downloads
7
+ * @param never_ask_function callback if android permissions are set to `never_ask_again`
8
+ * @returns
9
+ */
10
+ export async function localDownload(
11
+ uri: string,
12
+ never_ask_function?: () => void | undefined
13
+ ): Promise<void> {
14
+ const granted = await requestStoragePermission()
15
+ if (granted !== 'granted') {
16
+ if (granted === PermissionsAndroid.RESULTS.NEVER_ASK_AGAIN) {
17
+ if (!never_ask_function)
18
+ Alert.alert(
19
+ 'Permission Required',
20
+ 'You have permanently denied storage access. Please enable it from settings.',
21
+ [
22
+ { text: 'Cancel', style: 'cancel' },
23
+ { text: 'Open Settings', onPress: () => Linking.openSettings() },
24
+ ]
25
+ )
26
+ else never_ask_function()
27
+ }
28
+ throw new Error('Permissions not granted')
29
+ }
30
+ return ReactNativeLocalDownload.localDownload(uri)
31
+ }
32
+
33
+ export const requestStoragePermission = async (): Promise<
34
+ typeof PermissionsAndroid.RESULTS.DENIED
35
+ > => {
36
+ if (Platform.OS !== 'android') return PermissionsAndroid.RESULTS.GRANTED
37
+
38
+ try {
39
+ if (Number(Platform.Version) >= 33) {
40
+ return 'granted'
41
+ }
42
+
43
+ const hasPermission = await PermissionsAndroid.check(
44
+ PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE
45
+ )
46
+ if (hasPermission) {
47
+ return 'granted'
48
+ }
49
+
50
+ const granted = await PermissionsAndroid.request(
51
+ PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
52
+ {
53
+ title: 'Storage Permission',
54
+ message: 'This app needs access to your storage to download files.',
55
+ buttonPositive: 'OK',
56
+ }
57
+ )
58
+ return granted
59
+ } catch (err) {
60
+ console.warn(err)
61
+ return PermissionsAndroid.RESULTS.DENIED
62
+ }
63
+ }
64
+