|
| 1 | +package com.davidcrespo.onewallet.data.repository |
| 2 | + |
| 3 | +import android.content.ContentValues |
| 4 | +import android.content.Context |
| 5 | +import android.os.Environment |
| 6 | +import android.provider.MediaStore |
| 7 | +import androidx.core.net.toUri |
| 8 | +import com.davidcrespo.onewallet.domain.di.DispatcherProvider |
| 9 | +import com.davidcrespo.onewallet.domain.repository.FileRepository |
| 10 | +import kotlinx.coroutines.withContext |
| 11 | +import java.io.OutputStreamWriter |
| 12 | + |
| 13 | +class FileRepositoryImpl( |
| 14 | + private val context: Context, |
| 15 | + private val dispatcher: DispatcherProvider |
| 16 | +) : FileRepository { |
| 17 | + |
| 18 | + override suspend fun saveToDownloads(fileName: String, content: String): Result<Unit> = withContext(dispatcher.io) { |
| 19 | + runCatching { |
| 20 | + val contentResolver = context.contentResolver |
| 21 | + val contentValues = ContentValues().apply { |
| 22 | + put(MediaStore.MediaColumns.DISPLAY_NAME, fileName) |
| 23 | + put(MediaStore.MediaColumns.MIME_TYPE, "text/csv") |
| 24 | + put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS) |
| 25 | + } |
| 26 | + |
| 27 | + val uri = contentResolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, contentValues) |
| 28 | + ?: throw Exception("Failed to create MediaStore entry") |
| 29 | + |
| 30 | + contentResolver.openOutputStream(uri)?.use { outputStream -> |
| 31 | + OutputStreamWriter(outputStream).use { writer -> |
| 32 | + writer.write(content) |
| 33 | + } |
| 34 | + } ?: throw Exception("Failed to open output stream") |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + override suspend fun readFromUri(uriString: String): Result<String> = withContext(dispatcher.io) { |
| 39 | + runCatching { |
| 40 | + val uri = uriString.toUri() |
| 41 | + context.contentResolver.openInputStream(uri)?.use { inputStream -> |
| 42 | + inputStream.bufferedReader().use { it.readText() } |
| 43 | + } ?: throw Exception("Failed to open input stream") |
| 44 | + } |
| 45 | + } |
| 46 | +} |
0 commit comments