Send files directly between devices over the internet - no cloud storage, no size limits.
TypeScript cross-platformdata-transferdecentralizedfile-sharingfile-transferhole-punchingopen-sourcep2ppeer-to-peerprivacyprivacy-tools
save received documents to Android Downloads via MediaStore (#30)
Denis Lupookov474d59c30874
diff --git a/apps/mobile/modules/media-store/android/build.gradle b/apps/mobile/modules/media-store/android/build.gradlenew file mode 100644index 0000000..f1fd58b--- /dev/null+++ b/apps/mobile/modules/media-store/android/build.gradle@@ -0,0 +1,15 @@+plugins {+ id 'com.android.library'+ id 'expo-module-gradle-plugin'+}++group = 'expo.modules'+version = '1.0.0'++android {+ namespace "expo.modules.mediastore"+ defaultConfig {+ versionCode 1+ versionName "1.0.0"+ }+}diff --git a/apps/mobile/modules/media-store/android/src/main/java/expo/modules/mediastore/MediaStoreModule.kt b/apps/mobile/modules/media-store/android/src/main/java/expo/modules/mediastore/MediaStoreModule.ktnew file mode 100644index 0000000..6be87a5--- /dev/null+++ b/apps/mobile/modules/media-store/android/src/main/java/expo/modules/mediastore/MediaStoreModule.kt@@ -0,0 +1,86 @@+package expo.modules.mediastore++import android.content.ContentValues+import android.content.Intent+import android.net.Uri+import android.os.Environment+import android.provider.MediaStore+import expo.modules.kotlin.exception.Exceptions+import expo.modules.kotlin.modules.Module+import expo.modules.kotlin.modules.ModuleDefinition+import java.io.File++private const val COPY_BUFFER_SIZE = 1024 * 1024++class MediaStoreModule : Module() {+ override fun definition() = ModuleDefinition {+ Name("MediaStore")++ // Streams a private file into the public Downloads collection and deletes the source.+ AsyncFunction("saveToDownloads") { srcPath: String, fileName: String, mimeType: String ->+ val context = appContext.reactContext ?: throw Exceptions.ReactContextLost()+ val resolver = context.contentResolver++ val srcFilePath = if (srcPath.startsWith("file://")) Uri.parse(srcPath).path ?: srcPath else srcPath+ val src = File(srcFilePath)+ if (!src.exists()) throw IllegalArgumentException("Source file does not exist: $srcPath")++ val pending = ContentValues().apply {+ put(MediaStore.Downloads.DISPLAY_NAME, fileName)+ if (mimeType.isNotEmpty()) put(MediaStore.Downloads.MIME_TYPE, mimeType)+ put(MediaStore.Downloads.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS)+ put(MediaStore.Downloads.IS_PENDING, 1)+ }++ val collection = MediaStore.Downloads.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)+ val itemUri = resolver.insert(collection, pending)+ ?: throw IllegalStateException("Failed to create Downloads entry for $fileName")++ try {+ resolver.openOutputStream(itemUri).use { output ->+ output ?: throw IllegalStateException("Failed to open Downloads output stream")+ src.inputStream().use { input -> input.copyTo(output, COPY_BUFFER_SIZE) }+ }+ } catch (e: Exception) {+ resolver.delete(itemUri, null, null)+ throw e+ }++ val finalized = resolver.update(+ itemUri,+ ContentValues().apply { put(MediaStore.Downloads.IS_PENDING, 0) },+ null,+ null+ )+ if (finalized == 0) {+ resolver.delete(itemUri, null, null)+ throw IllegalStateException("Failed to finalize Downloads entry for $fileName")+ }+ src.delete()++ itemUri.toString()+ }++ // Opens a saved Downloads item in an external viewer via ACTION_VIEW.+ AsyncFunction("openDownload") { contentUri: String, mimeType: String ->+ val context = appContext.reactContext ?: throw Exceptions.ReactContextLost()+ val intent = Intent(Intent.ACTION_VIEW).apply {+ setDataAndType(Uri.parse(contentUri), mimeType.ifEmpty { "*/*" })+ addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)+ addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+ }+ context.startActivity(Intent.createChooser(intent, null).apply {+ addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+ })+ }++ // Opens the system Downloads UI.+ AsyncFunction("openDownloadsFolder") {+ val context = appContext.reactContext ?: throw Exceptions.ReactContextLost()+ val intent = Intent(android.app.DownloadManager.ACTION_VIEW_DOWNLOADS).apply {+ addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+ }+ context.startActivity(intent)+ }+ }+}diff --git a/apps/mobile/modules/media-store/expo-module.config.json b/apps/mobile/modules/media-store/expo-module.config.jsonnew file mode 100644index 0000000..c2ac010--- /dev/null+++ b/apps/mobile/modules/media-store/expo-module.config.json@@ -0,0 +1,6 @@+{+ "platforms": ["android"],+ "android": {+ "modules": ["expo.modules.mediastore.MediaStoreModule"]+ }+}diff --git a/apps/mobile/modules/media-store/index.ts b/apps/mobile/modules/media-store/index.tsnew file mode 100644index 0000000..951480b--- /dev/null+++ b/apps/mobile/modules/media-store/index.ts@@ -0,0 +1,6 @@+export {+ isMediaStoreAvailable,+ saveToDownloads,+ openDownload,+ openDownloadsFolder+} from './src/MediaStoreModule'diff --git a/apps/mobile/modules/media-store/package.json b/apps/mobile/modules/media-store/package.jsonnew file mode 100644index 0000000..b9b2cb9--- /dev/null+++ b/apps/mobile/modules/media-store/package.json@@ -0,0 +1,5 @@+{+ "name": "media-store",+ "version": "1.0.0",+ "main": "index.ts"+}diff --git a/apps/mobile/modules/media-store/src/MediaStoreModule.ts b/apps/mobile/modules/media-store/src/MediaStoreModule.tsnew file mode 100644index 0000000..935e15e--- /dev/null+++ b/apps/mobile/modules/media-store/src/MediaStoreModule.ts@@ -0,0 +1,35 @@+import { requireOptionalNativeModule } from 'expo-modules-core'++interface MediaStoreNativeModule {+ saveToDownloads(srcPath: string, fileName: string, mimeType: string): Promise<string>+ openDownload(contentUri: string, mimeType: string): Promise<void>+ openDownloadsFolder(): Promise<void>+}++const nativeModule = requireOptionalNativeModule<MediaStoreNativeModule>('MediaStore')++function requireModule(): MediaStoreNativeModule {+ if (!nativeModule) throw new Error('MediaStore is only available on Android')+ return nativeModule+}++export function isMediaStoreAvailable(): boolean {+ return nativeModule != null+}++/** Streams a local file into the public Downloads collection. Returns the MediaStore content URI. */+export function saveToDownloads(+ srcPath: string,+ fileName: string,+ mimeType: string+): Promise<string> {+ return requireModule().saveToDownloads(srcPath, fileName, mimeType)+}++export function openDownload(contentUri: string, mimeType: string): Promise<void> {+ return requireModule().openDownload(contentUri, mimeType)+}++export function openDownloadsFolder(): Promise<void> {+ return requireModule().openDownloadsFolder()+}diff --git a/apps/mobile/src/transfer/receive/utils/completionToast.ts b/apps/mobile/src/transfer/receive/utils/completionToast.tsindex 8efa619..82a231e 100644--- a/apps/mobile/src/transfer/receive/utils/completionToast.ts+++ b/apps/mobile/src/transfer/receive/utils/completionToast.ts@@ -1,6 +1,7 @@import { Linking, Platform } from 'react-native'import type { SaveDestination } from '@altersend/domain'import { i18nextInstance } from '@altersend/locales'+import { openDownloadsFolder } from '@/modules/media-store'import type { ShowToastInput } from '@/src/components/Toast'interface BuildCompletionToastInput {@@ -27,9 +28,10 @@ export function buildCompletionToast({if (count === 0) return nullconst photosCount = destinations.filter((d) => d === 'photos').length- const filesystemCount = destinations.filter((d) => d === 'filesystem').length+ const nonPhotosCount = count - photosCount+ const hasDownloads = destinations.some((d) => d === 'downloads')- if (photosCount > 0 && filesystemCount > 0) {+ if (photosCount > 0 && nonPhotosCount > 0) {return {title: i18nextInstance.t('receive:summary.filesSaved', { count }),hint:@@ -52,11 +54,17 @@ export function buildCompletionToast({}}+ const showDownloadsAction = Platform.OS === 'android' && hasDownloads+return {title: i18nextInstance.t('receive:summary.savedInFiles', { count }),hint: Platform.OS === 'ios' ? i18nextInstance.t('common:files.alterSendFolder') : undefined,- actionLabel: Platform.OS === 'android' ? i18nextInstance.t('receive:actions.open') : undefined,- onPress: Platform.OS === 'ios' ? openFiles : undefined,+ actionLabel: showDownloadsAction ? i18nextInstance.t('receive:actions.open') : undefined,+ onPress: showDownloadsAction+ ? () => void openDownloadsFolder().catch(() => {})+ : Platform.OS === 'ios'+ ? openFiles+ : undefined,durationMs: LONG_DURATION_MS}}diff --git a/apps/mobile/src/transfer/receive/utils/downloadHandlers.ts b/apps/mobile/src/transfer/receive/utils/downloadHandlers.tsindex 3d656fb..b93bf9e 100644--- a/apps/mobile/src/transfer/receive/utils/downloadHandlers.ts+++ b/apps/mobile/src/transfer/receive/utils/downloadHandlers.ts@@ -1,5 +1,7 @@+import { Platform } from 'react-native'import * as MediaLibrary from 'expo-media-library'import type { SaveDestination } from '@altersend/domain'+import { isMediaStoreAvailable, saveToDownloads } from '@/modules/media-store'const IMAGE_EXTENSIONS = new Set(['jpg',@@ -26,6 +28,31 @@ function isMediaFile(fileName: string): boolean {return IMAGE_EXTENSIONS.has(ext) || VIDEO_EXTENSIONS.has(ext)}+const MIME_BY_EXT: Record<string, string> = {+ pdf: 'application/pdf',+ zip: 'application/zip',+ rar: 'application/vnd.rar',+ '7z': 'application/x-7z-compressed',+ gz: 'application/gzip',+ tar: 'application/x-tar',+ doc: 'application/msword',+ docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',+ xls: 'application/vnd.ms-excel',+ xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',+ ppt: 'application/vnd.ms-powerpoint',+ pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',+ txt: 'text/plain',+ csv: 'text/csv',+ json: 'application/json',+ mp3: 'audio/mpeg',+ wav: 'audio/wav',+ apk: 'application/vnd.android.package-archive'+}++export function guessMimeType(fileName: string): string {+ return MIME_BY_EXT[getExtension(fileName)] ?? 'application/octet-stream'+}+function toFilePath(uri: string): string {if (uri.startsWith('file://')) return urireturn `file://${uri}`@@ -42,6 +69,17 @@ export async function handleDownloadedFile(fileName: string): Promise<HandleDownloadedFileResult> {if (!isMediaFile(fileName)) {+ // Android: stream into the public Downloads collection so it's browsable in Files.+ // iOS exposes the app's Documents dir via the Files app already, so no export is needed.+ if (Platform.OS === 'android' && isMediaStoreAvailable()) {+ try {+ const contentUri = await saveToDownloads(localPath, fileName, guessMimeType(fileName))+ return { intended: 'downloads', destination: 'downloads', localPath: contentUri }+ } catch (err) {+ console.warn('handleDownloadedFile: saveToDownloads failed, keeping private copy', err)+ return { intended: 'downloads', destination: 'filesystem', localPath }+ }+ }return { intended: 'filesystem', destination: 'filesystem', localPath }}diff --git a/apps/mobile/src/transfer/receive/utils/fileRowUtils.tsx b/apps/mobile/src/transfer/receive/utils/fileRowUtils.tsxindex 6e7ae9f..28f63d1 100644--- a/apps/mobile/src/transfer/receive/utils/fileRowUtils.tsx+++ b/apps/mobile/src/transfer/receive/utils/fileRowUtils.tsx@@ -1,5 +1,5 @@import React from 'react'-import { Pressable, StyleSheet } from 'react-native'+import { Platform, Pressable, StyleSheet } from 'react-native'import { getFileKind, useTheme } from '@altersend/components'import { formatFileSize, type DownloadItemState } from '@altersend/domain'import { useTranslation } from '@altersend/locales'@@ -17,7 +17,8 @@ function getActionLabel(name: string, t: Translate): string {function getDestinationLabel(state: DownloadItemState | undefined, t: Translate): string {if (!state || state.destination === undefined) return ''if (state.destination === 'photos') return t('common:files.photos')- return t('common:files.downloads')+ if (state.destination === 'downloads') return t('common:files.downloads')+ return Platform.OS === 'ios' ? t('common:files.alterSendFolder') : t('common:files.files')}export function getFileMeta(diff --git a/apps/mobile/src/transfer/receive/utils/openCompletedFile.ts b/apps/mobile/src/transfer/receive/utils/openCompletedFile.tsindex 14ec0fa..ed1cf3c 100644--- a/apps/mobile/src/transfer/receive/utils/openCompletedFile.ts+++ b/apps/mobile/src/transfer/receive/utils/openCompletedFile.ts@@ -1,6 +1,8 @@import { Linking, Platform } from 'react-native'import * as Sharing from 'expo-sharing'import { transferStore } from '@altersend/domain'+import { openDownload } from '@/modules/media-store'+import { guessMimeType } from './downloadHandlers'function openPhotos(): void {const url = Platform.OS === 'ios' ? 'photos-redirect://' : 'content://media/internal/images/media'@@ -8,7 +10,8 @@ function openPhotos(): void {}export function openCompletedFile(offerKey: string): void {- const item = transferStore.getState().receiveDownloadStates[offerKey]+ const state = transferStore.getState()+ const item = state.receiveDownloadStates[offerKey]if (!item || item.status !== 'completed' || !item.savedTo) returnif (item.destination === 'photos') {@@ -16,6 +19,14 @@ export function openCompletedFile(offerKey: string): void {return}+ if (item.destination === 'downloads') {+ const offer = state.incomingFileOffers.find((f) => f.id === offerKey)+ void openDownload(item.savedTo, guessMimeType(offer?.name ?? '')).catch((err) =>+ console.error('openCompletedFile: openDownload failed', err)+ )+ return+ }+const uri = item.savedTo.startsWith('file://') ? item.savedTo : `file://${item.savedTo}`void Sharing.isAvailableAsync().then((available) => {diff --git a/packages/domain/src/receive/downloadModel.ts b/packages/domain/src/receive/downloadModel.tsindex d2f2440..f0a62af 100644--- a/packages/domain/src/receive/downloadModel.ts+++ b/packages/domain/src/receive/downloadModel.ts@@ -3,7 +3,7 @@ import { formatFileSize } from '../format'export type DownloadStatus = 'idle' | 'downloading' | 'completed' | 'failed'-export type SaveDestination = 'filesystem' | 'photos'+export type SaveDestination = 'filesystem' | 'photos' | 'downloads'export interface DownloadItemState {status: DownloadStatus