├── app
├── .gitignore
├── src
│ ├── main
│ │ ├── res
│ │ │ ├── values
│ │ │ │ ├── strings.xml
│ │ │ │ ├── themes.xml
│ │ │ │ └── colors.xml
│ │ │ ├── drawable
│ │ │ │ ├── upload_icon.png
│ │ │ │ ├── ic_launcher_foreground.xml
│ │ │ │ └── ic_launcher_background.xml
│ │ │ ├── mipmap-hdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ ├── mipmap-mdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ ├── mipmap-xhdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ ├── mipmap-xxhdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ ├── mipmap-xxxhdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ ├── mipmap-anydpi-v26
│ │ │ │ ├── ic_launcher.xml
│ │ │ │ └── ic_launcher_round.xml
│ │ │ └── xml
│ │ │ │ ├── backup_rules.xml
│ │ │ │ └── data_extraction_rules.xml
│ │ ├── java
│ │ │ └── com
│ │ │ │ └── example
│ │ │ │ └── androidapptouploadfile
│ │ │ │ ├── utils
│ │ │ │ ├── RetrofitErrorType.kt
│ │ │ │ ├── Constants.kt
│ │ │ │ ├── garbage
│ │ │ │ └── ExtentionFunctions.kt
│ │ │ │ ├── domain
│ │ │ │ ├── models
│ │ │ │ │ ├── UploadFileDomainModel.kt
│ │ │ │ │ └── UriDetailsDomainModel.kt
│ │ │ │ ├── repository
│ │ │ │ │ ├── local
│ │ │ │ │ │ └── DatastoreRepository.kt
│ │ │ │ │ └── remote
│ │ │ │ │ │ └── RemoteServerRepository.kt
│ │ │ │ └── usecase
│ │ │ │ │ ├── upload_use_case
│ │ │ │ │ ├── UploadUseCases.kt
│ │ │ │ │ └── UploadUseCasesImpl.kt
│ │ │ │ │ └── local_data_store_use_cases
│ │ │ │ │ ├── LocalDatastoreUseCases.kt
│ │ │ │ │ └── LocalDatastoreUseCasesImpl.kt
│ │ │ │ ├── presentation
│ │ │ │ ├── models
│ │ │ │ │ ├── UploadFileUiModel.kt
│ │ │ │ │ └── UriDetailsUiModel.kt
│ │ │ │ ├── ui
│ │ │ │ │ ├── components
│ │ │ │ │ │ ├── CircularLoading.kt
│ │ │ │ │ │ └── PermissionDialog.kt
│ │ │ │ │ ├── theme
│ │ │ │ │ │ ├── Color.kt
│ │ │ │ │ │ ├── Type.kt
│ │ │ │ │ │ └── Theme.kt
│ │ │ │ │ ├── main
│ │ │ │ │ │ ├── viewmodel
│ │ │ │ │ │ │ ├── states
│ │ │ │ │ │ │ │ └── MainScreenState.kt
│ │ │ │ │ │ │ └── MainViewModel.kt
│ │ │ │ │ │ ├── MainScreen.kt
│ │ │ │ │ │ └── services
│ │ │ │ │ │ │ └── UploadFileService.kt
│ │ │ │ │ └── MainActivity.kt
│ │ │ │ ├── mappers
│ │ │ │ │ ├── UploadFileDomainToUi.kt
│ │ │ │ │ ├── UriDetailsDomainModelToUiModel.kt
│ │ │ │ │ └── UriDetailsUiModelToDomainModel.kt
│ │ │ │ └── di
│ │ │ │ │ └── MainModule.kt
│ │ │ │ ├── data
│ │ │ │ ├── local
│ │ │ │ │ ├── models
│ │ │ │ │ │ └── UriDetailsLocalModel.kt
│ │ │ │ │ ├── mappers
│ │ │ │ │ │ ├── UriDetailsDomainModelToLocalModel.kt
│ │ │ │ │ │ └── UriDetailsLocalModelToDomainModel.kt
│ │ │ │ │ ├── di
│ │ │ │ │ │ └── LocalModule.kt
│ │ │ │ │ └── repository
│ │ │ │ │ │ └── DatastoreRepositoryImpl.kt
│ │ │ │ └── remote
│ │ │ │ │ ├── dtos
│ │ │ │ │ └── UploadFileDto.kt
│ │ │ │ │ ├── mappers
│ │ │ │ │ └── UploadFileDtoToDomain.kt
│ │ │ │ │ ├── api
│ │ │ │ │ ├── RetrofitApi.kt
│ │ │ │ │ └── UploadStreamRequestBody.kt
│ │ │ │ │ ├── repository
│ │ │ │ │ └── RemoteServerRepositoryImpl.kt
│ │ │ │ │ └── di
│ │ │ │ │ └── NetworkModule.kt
│ │ │ │ ├── MyApplication.kt
│ │ │ │ └── di
│ │ │ │ └── AppModule.kt
│ │ └── AndroidManifest.xml
│ ├── test
│ │ └── java
│ │ │ └── com
│ │ │ └── example
│ │ │ └── androidapptouploadfile
│ │ │ └── ExampleUnitTest.kt
│ └── androidTest
│ │ └── java
│ │ └── com
│ │ └── example
│ │ └── androidapptouploadfile
│ │ └── ExampleInstrumentedTest.kt
├── proguard-rules.pro
└── build.gradle.kts
├── .idea
├── .gitignore
├── compiler.xml
├── kotlinc.xml
├── vcs.xml
├── misc.xml
├── gradle.xml
└── deploymentTargetDropDown.xml
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── .gitignore
├── settings.gradle.kts
├── LICENSE
├── gradle.properties
├── README.md
├── gradlew.bat
└── gradlew
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | AndroidAppToUploadFile
3 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AhmedMaherHosny/AndroidAppToUploadFile/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/app/src/main/res/drawable/upload_icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AhmedMaherHosny/AndroidAppToUploadFile/HEAD/app/src/main/res/drawable/upload_icon.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AhmedMaherHosny/AndroidAppToUploadFile/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AhmedMaherHosny/AndroidAppToUploadFile/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AhmedMaherHosny/AndroidAppToUploadFile/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AhmedMaherHosny/AndroidAppToUploadFile/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AhmedMaherHosny/AndroidAppToUploadFile/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AhmedMaherHosny/AndroidAppToUploadFile/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AhmedMaherHosny/AndroidAppToUploadFile/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AhmedMaherHosny/AndroidAppToUploadFile/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AhmedMaherHosny/AndroidAppToUploadFile/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AhmedMaherHosny/AndroidAppToUploadFile/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/java/com/example/androidapptouploadfile/utils/RetrofitErrorType.kt:
--------------------------------------------------------------------------------
1 | package com.example.androidapptouploadfile.utils
2 |
3 | enum class RetrofitErrorType {
4 | NETWORK_ERROR
5 | }
--------------------------------------------------------------------------------
/.idea/compiler.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/kotlinc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/res/values/themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/androidapptouploadfile/domain/models/UploadFileDomainModel.kt:
--------------------------------------------------------------------------------
1 | package com.example.androidapptouploadfile.domain.models
2 |
3 | data class UploadFileDomainModel(
4 | val message: String,
5 | val startByte: Int,
6 | val endByte: Int,
7 | )
8 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/androidapptouploadfile/presentation/models/UploadFileUiModel.kt:
--------------------------------------------------------------------------------
1 | package com.example.androidapptouploadfile.presentation.models
2 |
3 | data class UploadFileUiModel(
4 | val message: String,
5 | val startByte: Int,
6 | val endByte: Int,
7 | )
8 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Tue Sep 26 11:02:32 EET 2023
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.0-bin.zip
5 | zipStoreBase=GRADLE_USER_HOME
6 | zipStorePath=wrapper/dists
7 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/caches
5 | /.idea/libraries
6 | /.idea/modules.xml
7 | /.idea/workspace.xml
8 | /.idea/navEditor.xml
9 | /.idea/assetWizardSettings.xml
10 | .DS_Store
11 | /build
12 | /captures
13 | .externalNativeBuild
14 | .cxx
15 | local.properties
16 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/androidapptouploadfile/domain/models/UriDetailsDomainModel.kt:
--------------------------------------------------------------------------------
1 | package com.example.androidapptouploadfile.domain.models
2 |
3 | data class UriDetailsDomainModel(
4 | val fileIdentifier : String? = null,
5 | val startByte : Long? = null,
6 | val progress : Int = 0
7 | )
8 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/androidapptouploadfile/presentation/models/UriDetailsUiModel.kt:
--------------------------------------------------------------------------------
1 | package com.example.androidapptouploadfile.presentation.models
2 |
3 | data class UriDetailsUiModel(
4 | val fileIdentifier : String? = null,
5 | var startByte : Long? = null,
6 | val progress : Int = 0
7 | )
8 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/androidapptouploadfile/data/local/models/UriDetailsLocalModel.kt:
--------------------------------------------------------------------------------
1 | package com.example.androidapptouploadfile.data.local.models
2 |
3 | data class UriDetailsLocalModel(
4 | val fileIdentifier : String? = null,
5 | val startByte : Long? = null,
6 | val progress : Int = 0
7 |
8 | )
9 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/androidapptouploadfile/presentation/ui/components/CircularLoading.kt:
--------------------------------------------------------------------------------
1 | package com.example.androidapptouploadfile.presentation.ui.components
2 |
3 | import androidx.compose.runtime.Composable
4 |
5 | @Composable
6 | fun CircularLoading(
7 |
8 | ) {
9 | CircularLoadingContent(
10 |
11 | )
12 | }
13 |
14 | @Composable
15 | fun CircularLoadingContent(
16 |
17 | ) {
18 |
19 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/example/androidapptouploadfile/utils/Constants.kt:
--------------------------------------------------------------------------------
1 | package com.example.androidapptouploadfile.utils
2 |
3 | object Constants {
4 | const val BASE_URL = "http://192.168.1.55:3000/api/"
5 | const val CHANNEL_ID = "upload_notification"
6 | const val NOTIFICATION_ID = 1
7 | const val NAME_OF_UPLOAD_NOTIFICATION = "upload_notification_channel"
8 | const val UPLOAD_PREFERENCES = "UPLOAD_PREFERENCES"
9 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/example/androidapptouploadfile/presentation/ui/theme/Color.kt:
--------------------------------------------------------------------------------
1 | package com.example.androidapptouploadfile.presentation.ui.theme
2 |
3 | import androidx.compose.ui.graphics.Color
4 |
5 | val Purple80 = Color(0xFFD0BCFF)
6 | val PurpleGrey80 = Color(0xFFCCC2DC)
7 | val Pink80 = Color(0xFFEFB8C8)
8 |
9 | val Purple40 = Color(0xFF6650a4)
10 | val PurpleGrey40 = Color(0xFF625b71)
11 | val Pink40 = Color(0xFF7D5260)
--------------------------------------------------------------------------------
/settings.gradle.kts:
--------------------------------------------------------------------------------
1 | pluginManagement {
2 | repositories {
3 | google()
4 | mavenCentral()
5 | gradlePluginPortal()
6 | }
7 | }
8 | dependencyResolutionManagement {
9 | repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
10 | repositories {
11 | google()
12 | mavenCentral()
13 | }
14 | }
15 |
16 | rootProject.name = "AndroidAppToUploadFile"
17 | include(":app")
18 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/androidapptouploadfile/data/remote/dtos/UploadFileDto.kt:
--------------------------------------------------------------------------------
1 | package com.example.androidapptouploadfile.data.remote.dtos
2 |
3 |
4 | import com.google.gson.annotations.SerializedName
5 |
6 | data class UploadFileDto(
7 | @SerializedName("endByte")
8 | val endByte: Int,
9 | @SerializedName("message")
10 | val message: String,
11 | @SerializedName("startByte")
12 | val startByte: Int
13 | )
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #FFBB86FC
4 | #FF6200EE
5 | #FF3700B3
6 | #FF03DAC5
7 | #FF018786
8 | #FF000000
9 | #FFFFFFFF
10 |
--------------------------------------------------------------------------------
/app/src/test/java/com/example/androidapptouploadfile/ExampleUnitTest.kt:
--------------------------------------------------------------------------------
1 | package com.example.androidapptouploadfile
2 |
3 | import org.junit.Test
4 |
5 | import org.junit.Assert.*
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * See [testing documentation](http://d.android.com/tools/testing).
11 | */
12 | class ExampleUnitTest {
13 | @Test
14 | fun addition_isCorrect() {
15 | assertEquals(4, 2 + 2)
16 | }
17 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/example/androidapptouploadfile/domain/repository/local/DatastoreRepository.kt:
--------------------------------------------------------------------------------
1 | package com.example.androidapptouploadfile.domain.repository.local
2 |
3 | import com.example.androidapptouploadfile.domain.models.UriDetailsDomainModel
4 |
5 | interface DatastoreRepository {
6 | suspend fun writeUriModelDetailsForUpload(uri:String, value: UriDetailsDomainModel)
7 | suspend fun readUriModelDetailsForUpload(uri:String) : UriDetailsDomainModel?
8 | suspend fun deleteUriDetailsAboutUpload(uri:String)
9 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/example/androidapptouploadfile/domain/usecase/upload_use_case/UploadUseCases.kt:
--------------------------------------------------------------------------------
1 | package com.example.androidapptouploadfile.domain.usecase.upload_use_case
2 |
3 | import com.example.androidapptouploadfile.domain.models.UploadFileDomainModel
4 | import okhttp3.MultipartBody
5 |
6 | interface UploadUseCases {
7 | suspend fun uploadFileToServerUseCase(
8 | contentRange: String,
9 | fileIdentifier: String,
10 | file: MultipartBody.Part
11 | ): UploadFileDomainModel
12 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/example/androidapptouploadfile/data/remote/mappers/UploadFileDtoToDomain.kt:
--------------------------------------------------------------------------------
1 | package com.example.androidapptouploadfile.data.remote.mappers
2 |
3 | import com.example.androidapptouploadfile.data.remote.dtos.UploadFileDto
4 | import com.example.androidapptouploadfile.domain.models.UploadFileDomainModel
5 |
6 | fun UploadFileDto.toUploadFileDomainModel(): UploadFileDomainModel {
7 | return UploadFileDomainModel(
8 | message = message,
9 | startByte = startByte,
10 | endByte = endByte
11 | )
12 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/example/androidapptouploadfile/presentation/mappers/UploadFileDomainToUi.kt:
--------------------------------------------------------------------------------
1 | package com.example.androidapptouploadfile.presentation.mappers
2 |
3 | import com.example.androidapptouploadfile.domain.models.UploadFileDomainModel
4 | import com.example.androidapptouploadfile.presentation.models.UploadFileUiModel
5 |
6 | fun UploadFileDomainModel.toUploadFileUiModel(): UploadFileUiModel {
7 | return UploadFileUiModel(
8 | message = message,
9 | startByte = startByte,
10 | endByte = endByte
11 | )
12 | }
--------------------------------------------------------------------------------
/app/src/main/res/xml/backup_rules.xml:
--------------------------------------------------------------------------------
1 |
8 |
9 |
13 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/androidapptouploadfile/presentation/ui/main/viewmodel/states/MainScreenState.kt:
--------------------------------------------------------------------------------
1 | package com.example.androidapptouploadfile.presentation.ui.main.viewmodel.states
2 |
3 | data class MainScreenState(
4 | val uploadStatus: UploadStatus = UploadStatus.CANCELED,
5 | val progress: Int = 0,
6 | val speed: Double? = 0.0,
7 | val timeRemaining: Double? = 0.0,
8 | val fileName : String? = null,
9 | val fileSize : Double = 0.0
10 | )
11 |
12 | enum class UploadStatus {
13 | UPLOADING, PAUSED, COMPLETED, CANCELED
14 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/example/androidapptouploadfile/data/local/mappers/UriDetailsDomainModelToLocalModel.kt:
--------------------------------------------------------------------------------
1 | package com.example.androidapptouploadfile.data.local.mappers
2 |
3 | import com.example.androidapptouploadfile.data.local.models.UriDetailsLocalModel
4 | import com.example.androidapptouploadfile.domain.models.UriDetailsDomainModel
5 |
6 | fun UriDetailsDomainModel.toUriDetailsLocalModel(): UriDetailsLocalModel =
7 | UriDetailsLocalModel(
8 | fileIdentifier = fileIdentifier,
9 | startByte = startByte,
10 | progress = progress
11 | )
--------------------------------------------------------------------------------
/app/src/main/java/com/example/androidapptouploadfile/data/local/mappers/UriDetailsLocalModelToDomainModel.kt:
--------------------------------------------------------------------------------
1 | package com.example.androidapptouploadfile.data.local.mappers
2 |
3 | import com.example.androidapptouploadfile.data.local.models.UriDetailsLocalModel
4 | import com.example.androidapptouploadfile.domain.models.UriDetailsDomainModel
5 |
6 | fun UriDetailsLocalModel.toUriDetailsDomainModel(): UriDetailsDomainModel =
7 | UriDetailsDomainModel(
8 | fileIdentifier = fileIdentifier,
9 | startByte = startByte,
10 | progress = progress
11 | )
--------------------------------------------------------------------------------
/app/src/main/java/com/example/androidapptouploadfile/domain/repository/remote/RemoteServerRepository.kt:
--------------------------------------------------------------------------------
1 | package com.example.androidapptouploadfile.domain.repository.remote
2 |
3 | import com.example.androidapptouploadfile.domain.models.UploadFileDomainModel
4 | import okhttp3.MultipartBody
5 | import okhttp3.RequestBody
6 | import java.io.File
7 |
8 | interface RemoteServerRepository {
9 | suspend fun uploadFileToServer(
10 | contentRange: String,
11 | fileIdentifier: String,
12 | file: MultipartBody.Part
13 | ): UploadFileDomainModel
14 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/example/androidapptouploadfile/domain/usecase/local_data_store_use_cases/LocalDatastoreUseCases.kt:
--------------------------------------------------------------------------------
1 | package com.example.androidapptouploadfile.domain.usecase.local_data_store_use_cases
2 |
3 | import com.example.androidapptouploadfile.domain.models.UriDetailsDomainModel
4 |
5 | interface LocalDatastoreUseCases {
6 | suspend fun writeUriModelDetailsForUploadUseCase(uri:String, value: UriDetailsDomainModel)
7 | suspend fun readUriModelDetailsForUploadUseCase(uri:String) : UriDetailsDomainModel?
8 | suspend fun deleteUriDetailsAboutUploadUseCase(uri:String)
9 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/example/androidapptouploadfile/presentation/mappers/UriDetailsDomainModelToUiModel.kt:
--------------------------------------------------------------------------------
1 | package com.example.androidapptouploadfile.presentation.mappers
2 |
3 | import com.example.androidapptouploadfile.data.local.models.UriDetailsLocalModel
4 | import com.example.androidapptouploadfile.domain.models.UriDetailsDomainModel
5 | import com.example.androidapptouploadfile.presentation.models.UriDetailsUiModel
6 |
7 | fun UriDetailsDomainModel.toUriDetailsUiModel(): UriDetailsUiModel =
8 | UriDetailsUiModel(
9 | fileIdentifier = fileIdentifier,
10 | startByte = startByte,
11 | progress = progress
12 | )
--------------------------------------------------------------------------------
/app/src/main/java/com/example/androidapptouploadfile/presentation/mappers/UriDetailsUiModelToDomainModel.kt:
--------------------------------------------------------------------------------
1 | package com.example.androidapptouploadfile.presentation.mappers
2 |
3 | import com.example.androidapptouploadfile.data.local.models.UriDetailsLocalModel
4 | import com.example.androidapptouploadfile.domain.models.UriDetailsDomainModel
5 | import com.example.androidapptouploadfile.presentation.models.UriDetailsUiModel
6 |
7 | fun UriDetailsUiModel.toUriDetailsDomainModel(): UriDetailsDomainModel =
8 | UriDetailsDomainModel(
9 | fileIdentifier = fileIdentifier,
10 | startByte = startByte,
11 | progress = progress
12 | )
--------------------------------------------------------------------------------
/app/src/main/res/xml/data_extraction_rules.xml:
--------------------------------------------------------------------------------
1 |
6 |
7 |
8 |
12 |
13 |
19 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/androidapptouploadfile/data/remote/api/RetrofitApi.kt:
--------------------------------------------------------------------------------
1 | package com.example.androidapptouploadfile.data.remote.api
2 |
3 | import android.adservices.common.AdTechIdentifier
4 | import com.example.androidapptouploadfile.data.remote.dtos.UploadFileDto
5 | import okhttp3.MultipartBody
6 | import retrofit2.http.Header
7 | import retrofit2.http.Multipart
8 | import retrofit2.http.POST
9 | import retrofit2.http.Part
10 | import retrofit2.http.Streaming
11 |
12 | interface RetrofitApi {
13 | @Streaming
14 | @Multipart
15 | @POST("upload/file")
16 | suspend fun uploadFile(
17 | @Header("Content-Range") contentRange: String,
18 | @Header("X-File-Identifier") fileIdentifier: String,
19 | @Part file: MultipartBody.Part
20 | ): UploadFileDto
21 | }
--------------------------------------------------------------------------------
/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
19 |
20 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/example/androidapptouploadfile/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | package com.example.androidapptouploadfile
2 |
3 | import androidx.test.platform.app.InstrumentationRegistry
4 | import androidx.test.ext.junit.runners.AndroidJUnit4
5 |
6 | import org.junit.Test
7 | import org.junit.runner.RunWith
8 |
9 | import org.junit.Assert.*
10 |
11 | /**
12 | * Instrumented test, which will execute on an Android device.
13 | *
14 | * See [testing documentation](http://d.android.com/tools/testing).
15 | */
16 | @RunWith(AndroidJUnit4::class)
17 | class ExampleInstrumentedTest {
18 | @Test
19 | fun useAppContext() {
20 | // Context of the app under test.
21 | val appContext = InstrumentationRegistry.getInstrumentation().targetContext
22 | assertEquals("com.example.androidapptouploadfile", appContext.packageName)
23 | }
24 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/example/androidapptouploadfile/domain/usecase/upload_use_case/UploadUseCasesImpl.kt:
--------------------------------------------------------------------------------
1 | package com.example.androidapptouploadfile.domain.usecase.upload_use_case
2 |
3 | import com.example.androidapptouploadfile.domain.models.UploadFileDomainModel
4 | import com.example.androidapptouploadfile.domain.repository.remote.RemoteServerRepository
5 | import okhttp3.MultipartBody
6 | import javax.inject.Inject
7 |
8 | class UploadUseCasesImpl @Inject constructor(
9 | private val remoteServerRepository: RemoteServerRepository
10 | ) : UploadUseCases {
11 | override suspend fun uploadFileToServerUseCase(
12 | contentRange: String,
13 | fileIdentifier: String,
14 | file: MultipartBody.Part
15 | ): UploadFileDomainModel {
16 | return remoteServerRepository.uploadFileToServer(contentRange, fileIdentifier, file)
17 | }
18 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/example/androidapptouploadfile/data/remote/repository/RemoteServerRepositoryImpl.kt:
--------------------------------------------------------------------------------
1 | package com.example.androidapptouploadfile.data.remote.repository
2 |
3 | import com.example.androidapptouploadfile.data.remote.api.RetrofitApi
4 | import com.example.androidapptouploadfile.data.remote.mappers.toUploadFileDomainModel
5 | import com.example.androidapptouploadfile.domain.models.UploadFileDomainModel
6 | import com.example.androidapptouploadfile.domain.repository.remote.RemoteServerRepository
7 | import okhttp3.MultipartBody
8 | import javax.inject.Inject
9 |
10 | class RemoteServerRepositoryImpl @Inject constructor(
11 | private val retrofitApi: RetrofitApi
12 | ) : RemoteServerRepository {
13 | override suspend fun uploadFileToServer(
14 | contentRange: String,
15 | fileIdentifier: String,
16 | file: MultipartBody.Part
17 | ): UploadFileDomainModel {
18 | return retrofitApi.uploadFile(contentRange, fileIdentifier, file).toUploadFileDomainModel()
19 | }
20 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/example/androidapptouploadfile/data/local/di/LocalModule.kt:
--------------------------------------------------------------------------------
1 | package com.example.androidapptouploadfile.data.local.di
2 |
3 | import android.content.Context
4 | import com.example.androidapptouploadfile.data.local.repository.DatastoreRepositoryImpl
5 | import com.example.androidapptouploadfile.domain.repository.local.DatastoreRepository
6 | import com.google.gson.Gson
7 | import com.google.gson.GsonBuilder
8 | import dagger.Module
9 | import dagger.Provides
10 | import dagger.hilt.InstallIn
11 | import dagger.hilt.android.qualifiers.ApplicationContext
12 | import dagger.hilt.components.SingletonComponent
13 | import javax.inject.Singleton
14 |
15 | @Module
16 | @InstallIn(SingletonComponent::class)
17 | object LocalModule {
18 |
19 | @Provides
20 | @Singleton
21 | fun provideGson(): Gson {
22 | return GsonBuilder().serializeNulls().setLenient().create()
23 | }
24 |
25 | @Singleton
26 | @Provides
27 | fun provideContext(@ApplicationContext context: Context) = context
28 | }
--------------------------------------------------------------------------------
/.idea/deploymentTargetDropDown.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/androidapptouploadfile/MyApplication.kt:
--------------------------------------------------------------------------------
1 | package com.example.androidapptouploadfile
2 |
3 | import android.app.Application
4 | import android.app.NotificationChannel
5 | import android.app.NotificationManager
6 | import android.content.Context
7 | import android.os.Build
8 | import com.example.androidapptouploadfile.utils.Constants.CHANNEL_ID
9 | import com.example.androidapptouploadfile.utils.Constants.NAME_OF_UPLOAD_NOTIFICATION
10 | import dagger.hilt.android.HiltAndroidApp
11 |
12 | @HiltAndroidApp
13 | class MyApplication : Application() {
14 | override fun onCreate() {
15 | super.onCreate()
16 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
17 | val channel = NotificationChannel(
18 | CHANNEL_ID,
19 | NAME_OF_UPLOAD_NOTIFICATION,
20 | NotificationManager.IMPORTANCE_HIGH
21 | )
22 | val notificationManager =
23 | getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
24 | notificationManager.createNotificationChannel(channel)
25 | }
26 | }
27 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/example/androidapptouploadfile/presentation/di/MainModule.kt:
--------------------------------------------------------------------------------
1 | package com.example.androidapptouploadfile.presentation.di
2 |
3 | import com.example.androidapptouploadfile.domain.usecase.local_data_store_use_cases.LocalDatastoreUseCases
4 | import com.example.androidapptouploadfile.domain.usecase.local_data_store_use_cases.LocalDatastoreUseCasesImpl
5 | import com.example.androidapptouploadfile.domain.usecase.upload_use_case.UploadUseCasesImpl
6 | import com.example.androidapptouploadfile.domain.usecase.upload_use_case.UploadUseCases
7 | import dagger.Binds
8 | import dagger.Module
9 | import dagger.hilt.InstallIn
10 | import dagger.hilt.android.components.ServiceComponent
11 | import dagger.hilt.android.scopes.ServiceScoped
12 |
13 | @Module
14 | @InstallIn(ServiceComponent::class)
15 | abstract class ServiceModule {
16 | @Binds
17 | @ServiceScoped
18 | abstract fun bindUploadUseCase(uploadUseCasesImpl: UploadUseCasesImpl): UploadUseCases
19 |
20 | @Binds
21 | @ServiceScoped
22 | abstract fun bindDatastoreUseCase(localDatastoreUseCasesImpl: LocalDatastoreUseCasesImpl): LocalDatastoreUseCases
23 | }
24 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2023 Ahmed Maher
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/androidapptouploadfile/presentation/ui/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package com.example.androidapptouploadfile.presentation.ui
2 |
3 | import android.os.Bundle
4 | import androidx.activity.ComponentActivity
5 | import androidx.activity.compose.setContent
6 | import androidx.compose.foundation.layout.fillMaxSize
7 | import androidx.compose.material3.MaterialTheme
8 | import androidx.compose.material3.Surface
9 | import androidx.compose.material3.Text
10 | import androidx.compose.runtime.Composable
11 | import androidx.compose.ui.Modifier
12 | import androidx.compose.ui.tooling.preview.Preview
13 | import com.example.androidapptouploadfile.presentation.ui.main.MainScreen
14 | import com.example.androidapptouploadfile.presentation.ui.theme.AndroidAppToUploadFileTheme
15 | import dagger.hilt.android.AndroidEntryPoint
16 |
17 | @AndroidEntryPoint
18 | class MainActivity : ComponentActivity() {
19 | override fun onCreate(savedInstanceState: Bundle?) {
20 | super.onCreate(savedInstanceState)
21 | setContent {
22 | AndroidAppToUploadFileTheme {
23 | MainScreen()
24 | }
25 | }
26 | }
27 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/example/androidapptouploadfile/di/AppModule.kt:
--------------------------------------------------------------------------------
1 | package com.example.androidapptouploadfile.di
2 |
3 | import com.example.androidapptouploadfile.data.local.repository.DatastoreRepositoryImpl
4 | import com.example.androidapptouploadfile.data.remote.repository.RemoteServerRepositoryImpl
5 | import com.example.androidapptouploadfile.domain.repository.local.DatastoreRepository
6 | import com.example.androidapptouploadfile.domain.repository.remote.RemoteServerRepository
7 | import com.example.androidapptouploadfile.domain.usecase.local_data_store_use_cases.LocalDatastoreUseCasesImpl
8 | import dagger.Binds
9 | import dagger.Module
10 | import dagger.hilt.InstallIn
11 | import dagger.hilt.components.SingletonComponent
12 | import javax.inject.Singleton
13 |
14 | @Module
15 | @InstallIn(SingletonComponent::class)
16 | abstract class AppModule {
17 | @Binds
18 | @Singleton
19 | abstract fun bindRemoteServerRepository(remoteServerRepositoryImpl: RemoteServerRepositoryImpl): RemoteServerRepository
20 |
21 | @Binds
22 | @Singleton
23 | abstract fun bindDatastoreRepository(datastoreRepositoryImpl: DatastoreRepositoryImpl): DatastoreRepository
24 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/example/androidapptouploadfile/presentation/ui/main/viewmodel/MainViewModel.kt:
--------------------------------------------------------------------------------
1 | package com.example.androidapptouploadfile.presentation.ui.main.viewmodel
2 |
3 | import androidx.compose.runtime.getValue
4 | import androidx.compose.runtime.mutableStateListOf
5 | import androidx.compose.runtime.mutableStateOf
6 | import androidx.compose.runtime.setValue
7 | import androidx.lifecycle.ViewModel
8 | import androidx.lifecycle.viewModelScope
9 | import com.example.androidapptouploadfile.presentation.ui.main.viewmodel.states.MainScreenState
10 | import kotlinx.coroutines.launch
11 |
12 | class MainViewModel : ViewModel() {
13 | var mainScreenState by mutableStateOf(MainScreenState())
14 | private set
15 |
16 | val visiblePermissionDialogQueue = mutableStateListOf()
17 |
18 | fun dismissDialog() {
19 | visiblePermissionDialogQueue.removeFirst()
20 | }
21 |
22 | fun onPermissionResult(
23 | permission: String,
24 | isGranted: Boolean
25 | ) {
26 | if (!isGranted && !visiblePermissionDialogQueue.contains(permission)) {
27 | visiblePermissionDialogQueue.add(permission)
28 | }
29 | }
30 |
31 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/example/androidapptouploadfile/presentation/ui/theme/Type.kt:
--------------------------------------------------------------------------------
1 | package com.example.androidapptouploadfile.presentation.ui.theme
2 |
3 | import androidx.compose.material3.Typography
4 | import androidx.compose.ui.text.TextStyle
5 | import androidx.compose.ui.text.font.FontFamily
6 | import androidx.compose.ui.text.font.FontWeight
7 | import androidx.compose.ui.unit.sp
8 |
9 | // Set of Material typography styles to start with
10 | val Typography = Typography(
11 | bodyLarge = TextStyle(
12 | fontFamily = FontFamily.Default,
13 | fontWeight = FontWeight.Normal,
14 | fontSize = 16.sp,
15 | lineHeight = 24.sp,
16 | letterSpacing = 0.5.sp
17 | )
18 | /* Other default text styles to override
19 | titleLarge = TextStyle(
20 | fontFamily = FontFamily.Default,
21 | fontWeight = FontWeight.Normal,
22 | fontSize = 22.sp,
23 | lineHeight = 28.sp,
24 | letterSpacing = 0.sp
25 | ),
26 | labelSmall = TextStyle(
27 | fontFamily = FontFamily.Default,
28 | fontWeight = FontWeight.Medium,
29 | fontSize = 11.sp,
30 | lineHeight = 16.sp,
31 | letterSpacing = 0.5.sp
32 | )
33 | */
34 | )
--------------------------------------------------------------------------------
/app/src/main/java/com/example/androidapptouploadfile/domain/usecase/local_data_store_use_cases/LocalDatastoreUseCasesImpl.kt:
--------------------------------------------------------------------------------
1 | package com.example.androidapptouploadfile.domain.usecase.local_data_store_use_cases
2 |
3 | import com.example.androidapptouploadfile.data.local.repository.DatastoreRepositoryImpl
4 | import com.example.androidapptouploadfile.domain.models.UriDetailsDomainModel
5 | import com.example.androidapptouploadfile.domain.repository.local.DatastoreRepository
6 | import javax.inject.Inject
7 |
8 | class LocalDatastoreUseCasesImpl @Inject constructor(
9 | private val datastoreRepository: DatastoreRepository
10 | ) : LocalDatastoreUseCases {
11 | override suspend fun writeUriModelDetailsForUploadUseCase(
12 | uri: String,
13 | value: UriDetailsDomainModel
14 | ) {
15 | datastoreRepository.writeUriModelDetailsForUpload(uri, value)
16 | }
17 |
18 | override suspend fun readUriModelDetailsForUploadUseCase(uri: String): UriDetailsDomainModel? =
19 | datastoreRepository.readUriModelDetailsForUpload(uri)
20 |
21 |
22 | override suspend fun deleteUriDetailsAboutUploadUseCase(uri: String) {
23 | datastoreRepository.deleteUriDetailsAboutUpload(uri)
24 | }
25 |
26 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/example/androidapptouploadfile/utils/garbage:
--------------------------------------------------------------------------------
1 | val lifecycleOwner = LocalLifecycleOwner.current
2 | DisposableEffect(key1 = lifecycleOwner, effect = {
3 | val eventObserver = LifecycleEventObserver { _, event ->
4 | when (event) {
5 | Lifecycle.Event.ON_START -> {
6 |
7 | }
8 |
9 | else -> {}
10 | }
11 | }
12 | lifecycleOwner.lifecycle.addObserver(eventObserver)
13 | onDispose {
14 | lifecycleOwner.lifecycle.removeObserver(eventObserver)
15 | }
16 | })
17 |
18 |
19 | // this below not worked //////////////////////
20 | fun Context.getActivity(): AppCompatActivity? = when (this) {
21 | is AppCompatActivity -> this
22 | is ContextWrapper -> baseContext.getActivity()
23 | else -> null
24 | }
25 |
26 | fun Uri.getRealPath(context: Context): String? {
27 | val projection = arrayOf(MediaStore.Images.Media.DATA)
28 | val cursor = context.contentResolver.query(this, projection, null, null, null)
29 | val columnIndex = cursor?.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
30 | cursor?.moveToFirst()
31 | val filePath = cursor?.getString(columnIndex!!)
32 | cursor?.close()
33 | return filePath
34 | }
35 | ////////////////////////////////////////////////
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. More details, visit
12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
13 | # org.gradle.parallel=true
14 | # AndroidX package structure to make it clearer which packages are bundled with the
15 | # Android operating system, and which are packaged with your app's APK
16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
17 | android.useAndroidX=true
18 | # Kotlin code style for this project: "official" or "obsolete":
19 | kotlin.code.style=official
20 | # Enables namespacing of each library's R class so that its R class includes only the
21 | # resources declared in the library itself and none from the library's dependencies,
22 | # thereby reducing the size of the R class for that library
23 | android.nonTransitiveRClass=true
--------------------------------------------------------------------------------
/app/src/main/java/com/example/androidapptouploadfile/data/remote/di/NetworkModule.kt:
--------------------------------------------------------------------------------
1 | package com.example.androidapptouploadfile.data.remote.di
2 |
3 | import com.example.androidapptouploadfile.data.remote.api.RetrofitApi
4 | import com.example.androidapptouploadfile.utils.Constants.BASE_URL
5 | import dagger.Module
6 | import dagger.Provides
7 | import dagger.hilt.InstallIn
8 | import dagger.hilt.components.SingletonComponent
9 | import okhttp3.OkHttpClient
10 | import okhttp3.logging.HttpLoggingInterceptor
11 | import retrofit2.Retrofit
12 | import retrofit2.converter.gson.GsonConverterFactory
13 | import java.util.concurrent.TimeUnit
14 | import javax.inject.Singleton
15 |
16 | @Module
17 | @InstallIn(SingletonComponent::class)
18 | object NetworkModule {
19 | @Provides
20 | @Singleton
21 | fun provideRetrofit(): Retrofit {
22 | val logging = HttpLoggingInterceptor()
23 | logging.setLevel(HttpLoggingInterceptor.Level.BODY)
24 | val client = OkHttpClient.Builder()
25 | .connectTimeout(10, TimeUnit.MINUTES)
26 | .writeTimeout(10, TimeUnit.MINUTES)
27 | .readTimeout(10, TimeUnit.MINUTES)
28 | .addInterceptor(logging)
29 | .build()
30 | return Retrofit.Builder()
31 | .baseUrl(BASE_URL)
32 | .addConverterFactory(GsonConverterFactory.create())
33 | .client(client)
34 | .build()
35 | }
36 |
37 | @Provides
38 | @Singleton
39 | fun provideModelApi(retrofit: Retrofit): RetrofitApi {
40 | return retrofit.create(RetrofitApi::class.java)
41 | }
42 |
43 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/example/androidapptouploadfile/data/remote/api/UploadStreamRequestBody.kt:
--------------------------------------------------------------------------------
1 | package com.example.androidapptouploadfile.data.remote.api
2 |
3 | import android.util.Log
4 | import okhttp3.MediaType
5 | import okhttp3.MediaType.Companion.toMediaTypeOrNull
6 | import okhttp3.RequestBody
7 | import okio.BufferedSink
8 | import java.io.InputStream
9 |
10 | class UploadStreamRequestBody(
11 | private val mediaType: String,
12 | private val inputStream: InputStream,
13 | private val onUploadProgress: (Int, Long, Long) -> Unit,
14 | ) : RequestBody() {
15 | private var startTime: Long = 0
16 |
17 | override fun contentLength(): Long = inputStream.available().toLong()
18 |
19 | override fun contentType(): MediaType? = mediaType.toMediaTypeOrNull()
20 |
21 | override fun writeTo(sink: BufferedSink) {
22 | val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
23 | var uploaded = 0L
24 | startTime = System.currentTimeMillis()
25 | inputStream.use { inputStream ->
26 | var read: Int
27 | while (inputStream.read(buffer).also { read = it } != -1) {
28 | sink.write(buffer, 0, read)
29 | uploaded += read
30 | val progress = (100 * uploaded / contentLength()).toInt()
31 | val currentTime = System.currentTimeMillis()
32 | val elapsedTime = currentTime - startTime
33 | val uploadSpeed = if (elapsedTime > 0) (uploaded / elapsedTime) * 1000 else 0L
34 | val estimatedTimeRemaining =
35 | if (uploadSpeed > 0) (contentLength() - uploaded) / uploadSpeed else 0L
36 | onUploadProgress(progress, uploadSpeed, estimatedTimeRemaining)
37 | }
38 | }
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
8 |
9 |
15 |
18 |
21 |
22 |
23 |
24 |
30 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
25 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/androidapptouploadfile/data/local/repository/DatastoreRepositoryImpl.kt:
--------------------------------------------------------------------------------
1 | package com.example.androidapptouploadfile.data.local.repository
2 |
3 | import android.content.Context
4 | import androidx.datastore.core.DataStore
5 | import androidx.datastore.preferences.core.Preferences
6 | import androidx.datastore.preferences.core.edit
7 | import androidx.datastore.preferences.core.stringPreferencesKey
8 | import androidx.datastore.preferences.preferencesDataStore
9 | import com.example.androidapptouploadfile.data.local.mappers.toUriDetailsDomainModel
10 | import com.example.androidapptouploadfile.data.local.mappers.toUriDetailsLocalModel
11 | import com.example.androidapptouploadfile.data.local.models.UriDetailsLocalModel
12 | import com.example.androidapptouploadfile.domain.models.UriDetailsDomainModel
13 | import com.example.androidapptouploadfile.domain.repository.local.DatastoreRepository
14 | import com.example.androidapptouploadfile.utils.Constants.UPLOAD_PREFERENCES
15 | import com.google.gson.Gson
16 | import kotlinx.coroutines.flow.first
17 | import kotlinx.coroutines.flow.map
18 | import javax.inject.Inject
19 |
20 |
21 | private val Context.dataStore: DataStore by preferencesDataStore(name = UPLOAD_PREFERENCES)
22 |
23 | class DatastoreRepositoryImpl @Inject constructor(
24 | private val context: Context,
25 | private val gson: Gson
26 | ) : DatastoreRepository {
27 | override suspend fun writeUriModelDetailsForUpload(uri: String, value: UriDetailsDomainModel) {
28 | val preferencesKey = stringPreferencesKey(uri)
29 | val serializedData = gson.toJson(value.toUriDetailsLocalModel())
30 | context.dataStore.edit { preferences ->
31 | preferences[preferencesKey] = serializedData
32 | }
33 | }
34 |
35 | override suspend fun readUriModelDetailsForUpload(uri: String): UriDetailsDomainModel? {
36 | val preferencesKey = stringPreferencesKey(uri)
37 | val preferences = context.dataStore.data.first()
38 | val serializedData = preferences[preferencesKey]
39 | return if (serializedData != null)
40 | gson.fromJson(serializedData, UriDetailsLocalModel::class.java)
41 | .toUriDetailsDomainModel()
42 | else
43 | null
44 | }
45 |
46 | override suspend fun deleteUriDetailsAboutUpload(uri: String) {
47 | val preferencesKey = stringPreferencesKey(uri)
48 | context.dataStore.edit { preferences ->
49 | preferences.remove(preferencesKey)
50 | }
51 | }
52 |
53 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/example/androidapptouploadfile/presentation/ui/theme/Theme.kt:
--------------------------------------------------------------------------------
1 | package com.example.androidapptouploadfile.presentation.ui.theme
2 |
3 | import android.app.Activity
4 | import android.os.Build
5 | import androidx.compose.foundation.isSystemInDarkTheme
6 | import androidx.compose.material3.MaterialTheme
7 | import androidx.compose.material3.darkColorScheme
8 | import androidx.compose.material3.dynamicDarkColorScheme
9 | import androidx.compose.material3.dynamicLightColorScheme
10 | import androidx.compose.material3.lightColorScheme
11 | import androidx.compose.runtime.Composable
12 | import androidx.compose.runtime.SideEffect
13 | import androidx.compose.ui.graphics.toArgb
14 | import androidx.compose.ui.platform.LocalContext
15 | import androidx.compose.ui.platform.LocalView
16 | import androidx.core.view.WindowCompat
17 |
18 | private val DarkColorScheme = darkColorScheme(
19 | primary = Purple80,
20 | secondary = PurpleGrey80,
21 | tertiary = Pink80
22 | )
23 |
24 | private val LightColorScheme = lightColorScheme(
25 | primary = Purple40,
26 | secondary = PurpleGrey40,
27 | tertiary = Pink40
28 |
29 | /* Other default colors to override
30 | background = Color(0xFFFFFBFE),
31 | surface = Color(0xFFFFFBFE),
32 | onPrimary = Color.White,
33 | onSecondary = Color.White,
34 | onTertiary = Color.White,
35 | onBackground = Color(0xFF1C1B1F),
36 | onSurface = Color(0xFF1C1B1F),
37 | */
38 | )
39 |
40 | @Composable
41 | fun AndroidAppToUploadFileTheme(
42 | darkTheme: Boolean = isSystemInDarkTheme(),
43 | // Dynamic color is available on Android 12+
44 | dynamicColor: Boolean = true,
45 | content: @Composable () -> Unit
46 | ) {
47 | val colorScheme = when {
48 | dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
49 | val context = LocalContext.current
50 | if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
51 | }
52 |
53 | darkTheme -> DarkColorScheme
54 | else -> LightColorScheme
55 | }
56 | val view = LocalView.current
57 | if (!view.isInEditMode) {
58 | SideEffect {
59 | val window = (view.context as Activity).window
60 | window.statusBarColor = colorScheme.primary.toArgb()
61 | WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme
62 | }
63 | }
64 |
65 | MaterialTheme(
66 | colorScheme = colorScheme,
67 | typography = Typography,
68 | content = content
69 | )
70 | }
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Android File Upload App with Jetpack Compose
2 |
3 | This Android application is designed to upload very large files by splitting them into chunks, using streams for efficient upload.
4 |
5 | https://github.com/AhmedMaherHosny/AndroidAppToUploadFile/assets/55118681/dfa8bea3-2737-4206-ab6e-2df3d9ae9a10
6 |
7 | ## Design Patterns and Tools
8 |
9 | ### 1. Android Jetpack Compose
10 | - The user interface of the application is built using Jetpack Compose, which allows for a more declarative and efficient way to create UI components.
11 |
12 | ### 2. Uncle Bob's Clean Architecture
13 | - The application follows Clean Architecture principles, separating concerns into layers: Presentation, Domain, and Data. This ensures a clear and maintainable codebase.
14 |
15 | ### 3. Coroutines
16 | - Coroutines are used to manage asynchronous operations, such as file uploads, in a concise and readable way.
17 |
18 | ### 4. Retrofit 2
19 | - Retrofit 2 is used for making HTTP requests to a remote server, facilitating the file upload process.
20 |
21 | ### 5. Foreground Service
22 | - The app utilizes a foreground service to ensure that file uploads continue even when the app is in the background or closed, providing a seamless user experience.
23 |
24 | ### 6. MVVM Architecture
25 | - The application employs the MVVM (Model-View-ViewModel) architectural pattern, separating the UI logic from the data handling and business logic.
26 |
27 | ### 7. Dagger Hilt
28 | - Dagger Hilt is used for dependency injection, making it easier to manage and provide dependencies throughout the application.
29 |
30 | ## Features
31 | 1. Real Time Notification
32 | 2. Upload Speed
33 | 3. Estimated Time Reamining
34 | 4. Upload Progress
35 | 5. Pause And Resume The Upload
36 |
37 | ## Getting Started
38 | 1. Clone the repository to your local machine.
39 | 2. Open the project in Android Studio.
40 | 3. Build and run the app on an Android emulator or physical device.
41 |
42 | ## Usage
43 | 1. Launch the app on your Android device.
44 | 2. Select a file you want to upload.
45 | 3. The app will split the file into chunks and start the upload process.
46 | 4. Monitor the progress, upload speed, and estimated time remaining in real-time on the UI.
47 | 5. The foreground service ensures that the upload continues even if you navigate away from the app.
48 |
49 | ## License
50 | This project is licensed under the MIT License. See the [LICENSE](https://github.com/AhmedMaherHosny/AndroidAppToUploadFile/blob/master/LICENSE) file for details.
51 |
52 | ---
53 |
54 | Enjoy using the Android File Upload App with Jetpack Compose! If you have any questions or encounter any issues, please don't hesitate to [create an issue](https://github.com/AhmedMaherHosny/AndroidAppToUploadFile/issues) on the GitHub repository.
55 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%" == "" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%" == "" set DIRNAME=.
29 | set APP_BASE_NAME=%~n0
30 | set APP_HOME=%DIRNAME%
31 |
32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
34 |
35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
37 |
38 | @rem Find java.exe
39 | if defined JAVA_HOME goto findJavaFromJavaHome
40 |
41 | set JAVA_EXE=java.exe
42 | %JAVA_EXE% -version >NUL 2>&1
43 | if "%ERRORLEVEL%" == "0" goto execute
44 |
45 | echo.
46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
47 | echo.
48 | echo Please set the JAVA_HOME variable in your environment to match the
49 | echo location of your Java installation.
50 |
51 | goto fail
52 |
53 | :findJavaFromJavaHome
54 | set JAVA_HOME=%JAVA_HOME:"=%
55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
56 |
57 | if exist "%JAVA_EXE%" goto execute
58 |
59 | echo.
60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
61 | echo.
62 | echo Please set the JAVA_HOME variable in your environment to match the
63 | echo location of your Java installation.
64 |
65 | goto fail
66 |
67 | :execute
68 | @rem Setup the command line
69 |
70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
71 |
72 |
73 | @rem Execute Gradle
74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
75 |
76 | :end
77 | @rem End local scope for the variables with windows NT shell
78 | if "%ERRORLEVEL%"=="0" goto mainEnd
79 |
80 | :fail
81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
82 | rem the _cmd.exe /c_ return code!
83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
84 | exit /b 1
85 |
86 | :mainEnd
87 | if "%OS%"=="Windows_NT" endlocal
88 |
89 | :omega
90 |
--------------------------------------------------------------------------------
/app/build.gradle.kts:
--------------------------------------------------------------------------------
1 | plugins {
2 | id("com.android.application")
3 | id("org.jetbrains.kotlin.android")
4 | kotlin("kapt")
5 | id("com.google.dagger.hilt.android")
6 | }
7 |
8 | android {
9 | namespace = "com.example.androidapptouploadfile"
10 | compileSdk = 34
11 |
12 | defaultConfig {
13 | applicationId = "com.example.androidapptouploadfile"
14 | minSdk = 24
15 | targetSdk = 33
16 | versionCode = 1
17 | versionName = "1.0"
18 |
19 | testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
20 | vectorDrawables {
21 | useSupportLibrary = true
22 | }
23 | }
24 |
25 | buildTypes {
26 | release {
27 | isMinifyEnabled = false
28 | proguardFiles(
29 | getDefaultProguardFile("proguard-android-optimize.txt"),
30 | "proguard-rules.pro"
31 | )
32 | }
33 | }
34 | compileOptions {
35 | sourceCompatibility = JavaVersion.VERSION_17
36 | targetCompatibility = JavaVersion.VERSION_17
37 | }
38 | kotlinOptions {
39 | jvmTarget = JavaVersion.VERSION_17.toString()
40 | }
41 | buildFeatures {
42 | compose = true
43 | }
44 | kotlin {
45 | jvmToolchain(17)
46 | }
47 | composeOptions {
48 | kotlinCompilerExtensionVersion = "1.4.3"
49 | }
50 | packaging {
51 | resources {
52 | excludes += "/META-INF/{AL2.0,LGPL2.1}"
53 | }
54 | }
55 | }
56 |
57 | dependencies {
58 |
59 | implementation("androidx.core:core-ktx:1.9.0")
60 | implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.6.2")
61 | implementation("androidx.lifecycle:lifecycle-service:2.6.2")
62 | implementation("androidx.activity:activity-compose:1.7.2")
63 | implementation(platform("androidx.compose:compose-bom:2023.03.00"))
64 | implementation("androidx.compose.ui:ui")
65 | implementation("androidx.compose.ui:ui-graphics")
66 | implementation("androidx.compose.ui:ui-tooling-preview")
67 | implementation("androidx.compose.material3:material3")
68 | implementation("androidx.appcompat:appcompat:1.6.1")
69 | testImplementation("junit:junit:4.13.2")
70 | androidTestImplementation("androidx.test.ext:junit:1.1.5")
71 | androidTestImplementation("androidx.test.espresso:espresso-core:3.5.1")
72 | androidTestImplementation(platform("androidx.compose:compose-bom:2023.03.00"))
73 | androidTestImplementation("androidx.compose.ui:ui-test-junit4")
74 | debugImplementation("androidx.compose.ui:ui-tooling")
75 | debugImplementation("androidx.compose.ui:ui-test-manifest")
76 |
77 | //coroutines
78 | implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.4")
79 |
80 | //dagger hilt
81 | implementation("com.google.dagger:hilt-android:2.44")
82 | implementation("androidx.hilt:hilt-navigation-compose:1.0.0")
83 | kapt("com.google.dagger:hilt-android-compiler:2.44")
84 |
85 | //retorfit2
86 | implementation("com.squareup.retrofit2:retrofit:2.9.0")
87 | implementation("com.squareup.okhttp3:okhttp:5.0.0-alpha.2")
88 | implementation("com.squareup.retrofit2:converter-gson:2.9.0")
89 | implementation("com.squareup.okhttp3:logging-interceptor:4.5.0")
90 |
91 | //permissions
92 | implementation("com.google.accompanist:accompanist-permissions:0.33.2-alpha")
93 |
94 | //dataStore
95 | implementation("androidx.datastore:datastore-preferences:1.0.0")
96 | }
97 | kapt {
98 | correctErrorTypes = true
99 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/example/androidapptouploadfile/presentation/ui/components/PermissionDialog.kt:
--------------------------------------------------------------------------------
1 | package com.example.androidapptouploadfile.presentation.ui.components
2 |
3 | import androidx.compose.material.icons.Icons
4 | import androidx.compose.material.icons.outlined.Warning
5 | import androidx.compose.material3.AlertDialog
6 | import androidx.compose.material3.Icon
7 | import androidx.compose.material3.Text
8 | import androidx.compose.material3.TextButton
9 | import androidx.compose.runtime.Composable
10 |
11 | @Composable
12 | fun PermissionDialog(
13 | permissionTextProvider: PermissionTextProvider,
14 | isPermanentlyDeclined: Boolean,
15 | onDismiss: () -> Unit,
16 | onOkClick: () -> Unit,
17 | onGoToAppSettingsClick: () -> Unit,
18 | ) {
19 | AlertDialog(
20 | onDismissRequest = onDismiss,
21 | icon = {
22 | Icon(
23 | imageVector = Icons.Outlined.Warning,
24 | contentDescription = null
25 | )
26 | },
27 | title = {
28 | Text(text = "Permission required")
29 | },
30 | text = {
31 | Text(
32 | text = permissionTextProvider.getDescription(
33 | isPermanentlyDeclined = isPermanentlyDeclined
34 | )
35 | )
36 | },
37 | confirmButton = {
38 | TextButton(
39 | onClick = {
40 | if (isPermanentlyDeclined) {
41 | onGoToAppSettingsClick()
42 | } else {
43 | onOkClick()
44 | }
45 | }
46 | ) {
47 | Text(
48 | text = if (isPermanentlyDeclined) {
49 | "Grant permission"
50 | } else {
51 | "OK"
52 | }
53 | )
54 | }
55 | },
56 | dismissButton = {
57 | TextButton(
58 | onClick = {
59 | onDismiss()
60 | }
61 | ) {
62 | Text("Dismiss")
63 | }
64 | },
65 | )
66 | }
67 |
68 | interface PermissionTextProvider {
69 | fun getDescription(isPermanentlyDeclined: Boolean): String
70 | }
71 |
72 | class ReadExternalStoragePermissionTextProvider : PermissionTextProvider {
73 | override fun getDescription(isPermanentlyDeclined: Boolean): String {
74 | return if (isPermanentlyDeclined) {
75 | "It seems you permanently declined read phone storage permission. " +
76 | "You can go to the app settings to grant it."
77 | } else {
78 | "This app needs access to your storage so that you can upload files."
79 | }
80 | }
81 | }
82 |
83 | class PostNotificationPermissionTextProvider : PermissionTextProvider {
84 | override fun getDescription(isPermanentlyDeclined: Boolean): String {
85 | return if (isPermanentlyDeclined) {
86 | "It seems you permanently declined notification permission. " +
87 | "You can go to the app settings to grant it."
88 | } else {
89 | "This app needs access to your notification so that you can track the progress of upload. "
90 | }
91 | }
92 | }
93 |
94 | class ForegroundServicesPermissionTextProvider : PermissionTextProvider {
95 | override fun getDescription(isPermanentlyDeclined: Boolean): String {
96 | return if (isPermanentlyDeclined) {
97 | "It seems you permanently declined running in the background permission. " +
98 | "You can go to the app settings to grant it."
99 | } else {
100 | "This app needs access to your background so that you can track the progress of upload even if the app is closed. "
101 | }
102 | }
103 | }
104 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/androidapptouploadfile/utils/ExtentionFunctions.kt:
--------------------------------------------------------------------------------
1 | package com.example.androidapptouploadfile.utils
2 |
3 | import android.app.Activity
4 | import android.content.ContentResolver
5 | import android.content.ContentUris
6 | import android.content.Context
7 | import android.content.ContextWrapper
8 | import android.content.Intent
9 | import android.database.Cursor
10 | import android.net.Uri
11 | import android.os.Build
12 | import android.os.Environment
13 | import android.provider.DocumentsContract
14 | import android.provider.MediaStore
15 | import android.provider.OpenableColumns
16 | import android.provider.Settings
17 | import com.example.androidapptouploadfile.presentation.ui.main.services.UploadFileService
18 | import java.io.ByteArrayOutputStream
19 | import java.util.UUID
20 |
21 |
22 | fun Context.findActivity(): Activity {
23 | var context = this
24 | while (context is ContextWrapper) {
25 | if (context is Activity) return context
26 | context = context.baseContext
27 | }
28 | throw IllegalStateException("Permissions should be called in the context of an Activity")
29 | }
30 |
31 | fun Context.openAppSettings() {
32 | Intent(
33 | Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
34 | Uri.fromParts("package", this.packageName, null)
35 | ).also {
36 | it.flags = Intent.FLAG_ACTIVITY_NEW_TASK
37 | this.startActivity(it)
38 | }
39 | }
40 |
41 | fun Long.formatTime(): String {
42 | val minutes = this / 60
43 | val hours = minutes / 60
44 | val days = hours / 24
45 | val weeks = days / 7
46 | val months = weeks / 4
47 | val years = months / 12
48 |
49 | return when {
50 | years > 0 -> "$years years left"
51 | months > 0 -> "$months months left"
52 | weeks > 0 -> "$weeks weeks left"
53 | days > 0 -> "$days days left"
54 | hours > 0 -> "$hours hours left"
55 | minutes > 0 -> "$minutes minutes left"
56 | else -> "$this seconds left"
57 | }
58 | }
59 |
60 | fun Long.formatSpeed(): String {
61 | val bytesPerSecond = this.toDouble()
62 |
63 | val kilobytesPerSecond = bytesPerSecond / 1024.0
64 | val megabytesPerSecond = kilobytesPerSecond / 1024.0
65 | val gigabytesPerSecond = megabytesPerSecond / 1024.0
66 |
67 | return when {
68 | gigabytesPerSecond >= 1.0 -> String.format("%.2f GB/s", gigabytesPerSecond)
69 | megabytesPerSecond >= 1.0 -> String.format("%.2f MB/s", megabytesPerSecond)
70 | kilobytesPerSecond >= 1.0 -> String.format("%.2f KB/s", kilobytesPerSecond)
71 | else -> String.format("%.2f B/s", bytesPerSecond)
72 | }
73 | }
74 |
75 | fun Uri.getFileName(contentResolver: ContentResolver): String? {
76 | var result: String? = null
77 | if (this.scheme == "content") {
78 | val cursor: Cursor? = contentResolver.query(this, null, null, null, null)
79 | cursor.use { cursor ->
80 | if (cursor != null && cursor.moveToFirst()) {
81 | result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME))
82 | }
83 | }
84 | }
85 | if (result == null) {
86 | result = this.path
87 | val cut = result!!.lastIndexOf('/')
88 | if (cut != -1) {
89 | result = result?.substring(cut + 1)
90 | }
91 | }
92 | return result
93 | }
94 |
95 | fun Uri.getFileSize(contentResolver: ContentResolver): Long {
96 | var result: Long = -1
97 | if (this.scheme == "content") {
98 | val cursor: Cursor? = contentResolver.query(this, null, null, null, null)
99 | try {
100 | if (cursor != null && cursor.moveToFirst()) {
101 | result = cursor.getLong(cursor.getColumnIndex(OpenableColumns.SIZE))
102 | }
103 | } finally {
104 | cursor?.close()
105 | }
106 | }
107 | return result
108 | }
109 |
110 | fun Uri.readBytes(context: Context): ByteArray? {
111 | val contentResolver: ContentResolver = context.contentResolver
112 | try {
113 | contentResolver.openInputStream(this)?.use { inputStream ->
114 | val buffer = ByteArrayOutputStream()
115 | val bufferSize = 1024
116 | val data = ByteArray(bufferSize)
117 | var bytesRead: Int
118 | while (inputStream.read(data, 0, bufferSize).also { bytesRead = it } != -1) {
119 | buffer.write(data, 0, bytesRead)
120 | }
121 | return buffer.toByteArray()
122 | }
123 | } catch (e: Exception) {
124 | e.printStackTrace()
125 | }
126 | return null
127 | }
128 |
129 | fun Context.sendCommandToUploadService(data: Uri, action: String) =
130 | Intent(this, UploadFileService::class.java).also {
131 | it.action = action
132 | it.data = data
133 | this.startService(it)
134 | }
135 |
136 | fun generateUUIDv4(): UUID {
137 | return UUID.randomUUID()
138 | }
139 |
140 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | #
4 | # Copyright 2015 the original author or authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | ##
21 | ## Gradle start up script for UN*X
22 | ##
23 | ##############################################################################
24 |
25 | # Attempt to set APP_HOME
26 | # Resolve links: $0 may be a link
27 | PRG="$0"
28 | # Need this for relative symlinks.
29 | while [ -h "$PRG" ] ; do
30 | ls=`ls -ld "$PRG"`
31 | link=`expr "$ls" : '.*-> \(.*\)$'`
32 | if expr "$link" : '/.*' > /dev/null; then
33 | PRG="$link"
34 | else
35 | PRG=`dirname "$PRG"`"/$link"
36 | fi
37 | done
38 | SAVED="`pwd`"
39 | cd "`dirname \"$PRG\"`/" >/dev/null
40 | APP_HOME="`pwd -P`"
41 | cd "$SAVED" >/dev/null
42 |
43 | APP_NAME="Gradle"
44 | APP_BASE_NAME=`basename "$0"`
45 |
46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
48 |
49 | # Use the maximum available, or set MAX_FD != -1 to use that value.
50 | MAX_FD="maximum"
51 |
52 | warn () {
53 | echo "$*"
54 | }
55 |
56 | die () {
57 | echo
58 | echo "$*"
59 | echo
60 | exit 1
61 | }
62 |
63 | # OS specific support (must be 'true' or 'false').
64 | cygwin=false
65 | msys=false
66 | darwin=false
67 | nonstop=false
68 | case "`uname`" in
69 | CYGWIN* )
70 | cygwin=true
71 | ;;
72 | Darwin* )
73 | darwin=true
74 | ;;
75 | MINGW* )
76 | msys=true
77 | ;;
78 | NONSTOP* )
79 | nonstop=true
80 | ;;
81 | esac
82 |
83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
84 |
85 |
86 | # Determine the Java command to use to start the JVM.
87 | if [ -n "$JAVA_HOME" ] ; then
88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
89 | # IBM's JDK on AIX uses strange locations for the executables
90 | JAVACMD="$JAVA_HOME/jre/sh/java"
91 | else
92 | JAVACMD="$JAVA_HOME/bin/java"
93 | fi
94 | if [ ! -x "$JAVACMD" ] ; then
95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
96 |
97 | Please set the JAVA_HOME variable in your environment to match the
98 | location of your Java installation."
99 | fi
100 | else
101 | JAVACMD="java"
102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
103 |
104 | Please set the JAVA_HOME variable in your environment to match the
105 | location of your Java installation."
106 | fi
107 |
108 | # Increase the maximum file descriptors if we can.
109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
110 | MAX_FD_LIMIT=`ulimit -H -n`
111 | if [ $? -eq 0 ] ; then
112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
113 | MAX_FD="$MAX_FD_LIMIT"
114 | fi
115 | ulimit -n $MAX_FD
116 | if [ $? -ne 0 ] ; then
117 | warn "Could not set maximum file descriptor limit: $MAX_FD"
118 | fi
119 | else
120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
121 | fi
122 | fi
123 |
124 | # For Darwin, add options to specify how the application appears in the dock
125 | if $darwin; then
126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
127 | fi
128 |
129 | # For Cygwin or MSYS, switch paths to Windows format before running java
130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
133 |
134 | JAVACMD=`cygpath --unix "$JAVACMD"`
135 |
136 | # We build the pattern for arguments to be converted via cygpath
137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
138 | SEP=""
139 | for dir in $ROOTDIRSRAW ; do
140 | ROOTDIRS="$ROOTDIRS$SEP$dir"
141 | SEP="|"
142 | done
143 | OURCYGPATTERN="(^($ROOTDIRS))"
144 | # Add a user-defined pattern to the cygpath arguments
145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
147 | fi
148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
149 | i=0
150 | for arg in "$@" ; do
151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
153 |
154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
156 | else
157 | eval `echo args$i`="\"$arg\""
158 | fi
159 | i=`expr $i + 1`
160 | done
161 | case $i in
162 | 0) set -- ;;
163 | 1) set -- "$args0" ;;
164 | 2) set -- "$args0" "$args1" ;;
165 | 3) set -- "$args0" "$args1" "$args2" ;;
166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;;
167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
172 | esac
173 | fi
174 |
175 | # Escape application args
176 | save () {
177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
178 | echo " "
179 | }
180 | APP_ARGS=`save "$@"`
181 |
182 | # Collect all arguments for the java command, following the shell quoting and substitution rules
183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
184 |
185 | exec "$JAVACMD" "$@"
186 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/androidapptouploadfile/presentation/ui/main/MainScreen.kt:
--------------------------------------------------------------------------------
1 | package com.example.androidapptouploadfile.presentation.ui.main
2 |
3 | import android.Manifest
4 | import android.app.Activity
5 | import android.content.Intent
6 | import android.os.Build
7 | import androidx.activity.compose.ManagedActivityResultLauncher
8 | import androidx.activity.compose.rememberLauncherForActivityResult
9 | import androidx.activity.result.ActivityResult
10 | import androidx.activity.result.contract.ActivityResultContracts
11 | import androidx.compose.foundation.background
12 | import androidx.compose.foundation.layout.Arrangement
13 | import androidx.compose.foundation.layout.Column
14 | import androidx.compose.foundation.layout.Row
15 | import androidx.compose.foundation.layout.Spacer
16 | import androidx.compose.foundation.layout.fillMaxSize
17 | import androidx.compose.foundation.layout.fillMaxWidth
18 | import androidx.compose.foundation.layout.height
19 | import androidx.compose.foundation.layout.padding
20 | import androidx.compose.material.icons.Icons
21 | import androidx.compose.material.icons.outlined.Clear
22 | import androidx.compose.material.icons.outlined.Send
23 | import androidx.compose.material3.Button
24 | import androidx.compose.material3.Icon
25 | import androidx.compose.material3.IconButton
26 | import androidx.compose.material3.MaterialTheme
27 | import androidx.compose.material3.Text
28 | import androidx.compose.runtime.Composable
29 | import androidx.compose.ui.Alignment
30 | import androidx.compose.ui.Modifier
31 | import androidx.compose.ui.draw.rotate
32 | import androidx.compose.ui.graphics.Color
33 | import androidx.compose.ui.platform.LocalContext
34 | import androidx.compose.ui.text.style.TextOverflow
35 | import androidx.compose.ui.unit.dp
36 | import androidx.core.app.ActivityCompat.shouldShowRequestPermissionRationale
37 | import androidx.hilt.navigation.compose.hiltViewModel
38 | import com.example.androidapptouploadfile.presentation.ui.main.services.UploadFileService
39 | import com.example.androidapptouploadfile.presentation.ui.components.ForegroundServicesPermissionTextProvider
40 | import com.example.androidapptouploadfile.presentation.ui.components.PermissionDialog
41 | import com.example.androidapptouploadfile.presentation.ui.components.PostNotificationPermissionTextProvider
42 | import com.example.androidapptouploadfile.presentation.ui.components.ReadExternalStoragePermissionTextProvider
43 | import com.example.androidapptouploadfile.presentation.ui.main.viewmodel.MainViewModel
44 | import com.example.androidapptouploadfile.presentation.ui.main.viewmodel.states.MainScreenState
45 | import com.example.androidapptouploadfile.presentation.ui.main.viewmodel.states.UploadStatus
46 | import com.example.androidapptouploadfile.utils.findActivity
47 | import com.example.androidapptouploadfile.utils.openAppSettings
48 | import com.example.androidapptouploadfile.utils.sendCommandToUploadService
49 |
50 |
51 | @Composable
52 | fun MainScreen(
53 | viewModel: MainViewModel = hiltViewModel()
54 | ) {
55 | val context = LocalContext.current
56 | val activity = context.findActivity()
57 | val state = viewModel.mainScreenState
58 | val permissionsToRequest = mutableListOf()
59 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
60 | permissionsToRequest.add(Manifest.permission.READ_EXTERNAL_STORAGE)
61 | }
62 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
63 | permissionsToRequest.addAll(
64 | listOf(
65 | Manifest.permission.POST_NOTIFICATIONS,
66 | Manifest.permission.READ_MEDIA_AUDIO,
67 | Manifest.permission.READ_MEDIA_IMAGES,
68 | Manifest.permission.READ_MEDIA_VIDEO,
69 | )
70 | )
71 | }
72 | val dialogQueue = viewModel.visiblePermissionDialogQueue
73 | val multiplePermissionResultLauncher = rememberLauncherForActivityResult(
74 | contract = ActivityResultContracts.RequestMultiplePermissions(),
75 | onResult = { perms ->
76 | permissionsToRequest.forEach { permission ->
77 | viewModel.onPermissionResult(
78 | permission = permission,
79 | isGranted = perms[permission] == true
80 | )
81 | }
82 | }
83 | )
84 | dialogQueue
85 | .reversed()
86 | .forEach { permission ->
87 | PermissionDialog(
88 | permissionTextProvider = when (permission) {
89 | Manifest.permission.READ_EXTERNAL_STORAGE -> ReadExternalStoragePermissionTextProvider()
90 | Manifest.permission.POST_NOTIFICATIONS -> PostNotificationPermissionTextProvider()
91 | Manifest.permission.FOREGROUND_SERVICE -> ForegroundServicesPermissionTextProvider()
92 | else -> return@forEach
93 | },
94 | isPermanentlyDeclined = !shouldShowRequestPermissionRationale(
95 | activity, permission
96 | ),
97 | onOkClick = {
98 | viewModel.dismissDialog()
99 | multiplePermissionResultLauncher.launch(
100 | arrayOf(permission)
101 | )
102 | },
103 | onDismiss = viewModel::dismissDialog,
104 | onGoToAppSettingsClick = { context.openAppSettings() }
105 | )
106 | }
107 |
108 | val pickFileLauncher = rememberLauncherForActivityResult(
109 | contract = ActivityResultContracts.StartActivityForResult()
110 | ) { result: ActivityResult ->
111 | if (result.resultCode == Activity.RESULT_OK) {
112 | val data: Intent? = result.data
113 | val fileUri = data?.data
114 | if (fileUri != null) {
115 | context.sendCommandToUploadService(
116 | data = fileUri,
117 | action = UploadFileService.UploadFileServiceActions.START.toString()
118 | )
119 | } else {
120 | // handle uri is null
121 | }
122 | }
123 | }
124 | MainScreenContent(state = state, pickFileLauncher) {
125 | multiplePermissionResultLauncher.launch(
126 | permissionsToRequest.toTypedArray()
127 | )
128 | }
129 | }
130 |
131 |
132 | @Composable
133 | fun MainScreenContent(
134 | state: MainScreenState,
135 | pickFileLauncher: ManagedActivityResultLauncher,
136 | launchPermissions: () -> Unit,
137 | ) {
138 | Column(
139 | modifier = Modifier
140 | .fillMaxSize()
141 | ) {
142 | Row(
143 | modifier = Modifier
144 | .fillMaxWidth()
145 | .background(MaterialTheme.colorScheme.primary)
146 | ) {
147 | Spacer(modifier = Modifier.weight(1f))
148 | if ((state.uploadStatus == UploadStatus.CANCELED || state.uploadStatus == UploadStatus.COMPLETED) && state.fileName != null) {
149 | IconButton(onClick = { }) {
150 | Icon(
151 | imageVector = Icons.Outlined.Send,
152 | contentDescription = "upload file",
153 | tint = Color.White,
154 | modifier = Modifier
155 | .rotate(-25f)
156 | )
157 | }
158 | }
159 | if (state.uploadStatus == UploadStatus.UPLOADING || state.uploadStatus == UploadStatus.PAUSED) {
160 | IconButton(onClick = { }) {
161 | Icon(
162 | imageVector = Icons.Outlined.Clear,
163 | contentDescription = "cancel the upload",
164 | tint = Color.White,
165 | )
166 | }
167 | }
168 |
169 | }
170 | Column(
171 | modifier = Modifier
172 | .fillMaxSize()
173 | .padding(30.dp),
174 | horizontalAlignment = Alignment.CenterHorizontally,
175 | verticalArrangement = Arrangement.Center,
176 | ) {
177 | if (state.uploadStatus == UploadStatus.UPLOADING) {
178 | Text(
179 | text = "Upload speed : ${state.speed} Mega/Sec",
180 | overflow = TextOverflow.Ellipsis,
181 | maxLines = 1
182 | )
183 | Text(
184 | text = "time remaining : ${state.timeRemaining} Min",
185 | overflow = TextOverflow.Ellipsis,
186 | maxLines = 1
187 | )
188 | Text(
189 | text = "progress : ${state.progress}%",
190 | overflow = TextOverflow.Ellipsis,
191 | maxLines = 1
192 | )
193 | }
194 | Button(onClick = {
195 | launchPermissions()
196 | // i want to check if storage permission granted or no to open the gallery
197 | pickFileLauncher.launch(Intent(Intent.ACTION_OPEN_DOCUMENT).apply { type = "*/*" })
198 | }) {
199 | Text(text = "Choose a file")
200 | }
201 | Spacer(modifier = Modifier.height(10.dp))
202 | if (state.fileName != null) {
203 | Text(
204 | text = "File name : ${state.fileName}",
205 | overflow = TextOverflow.Ellipsis,
206 | maxLines = 1
207 | )
208 | Text(
209 | text = "File Size : ${state.fileSize} Mega",
210 | overflow = TextOverflow.Ellipsis,
211 | maxLines = 1
212 | )
213 | }
214 | }
215 | }
216 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/example/androidapptouploadfile/presentation/ui/main/services/UploadFileService.kt:
--------------------------------------------------------------------------------
1 | package com.example.androidapptouploadfile.presentation.ui.main.services
2 |
3 | import android.app.Notification
4 | import android.app.PendingIntent
5 | import android.content.Intent
6 | import android.net.Uri
7 | import androidx.core.app.NotificationCompat
8 | import androidx.lifecycle.LifecycleService
9 | import androidx.lifecycle.MutableLiveData
10 | import androidx.lifecycle.lifecycleScope
11 | import com.example.androidapptouploadfile.R
12 | import com.example.androidapptouploadfile.domain.usecase.local_data_store_use_cases.LocalDatastoreUseCases
13 | import com.example.androidapptouploadfile.domain.usecase.upload_use_case.UploadUseCases
14 | import com.example.androidapptouploadfile.presentation.mappers.toUriDetailsDomainModel
15 | import com.example.androidapptouploadfile.presentation.mappers.toUriDetailsUiModel
16 | import com.example.androidapptouploadfile.presentation.models.UriDetailsUiModel
17 | import com.example.androidapptouploadfile.presentation.ui.MainActivity
18 | import com.example.androidapptouploadfile.utils.Constants.CHANNEL_ID
19 | import com.example.androidapptouploadfile.utils.Constants.NOTIFICATION_ID
20 | import com.example.androidapptouploadfile.utils.RetrofitErrorType
21 | import com.example.androidapptouploadfile.utils.formatSpeed
22 | import com.example.androidapptouploadfile.utils.formatTime
23 | import com.example.androidapptouploadfile.utils.generateUUIDv4
24 | import com.example.androidapptouploadfile.utils.getFileName
25 | import com.example.androidapptouploadfile.utils.getFileSize
26 | import dagger.hilt.android.AndroidEntryPoint
27 | import kotlinx.coroutines.CoroutineExceptionHandler
28 | import kotlinx.coroutines.Dispatchers
29 | import kotlinx.coroutines.flow.MutableSharedFlow
30 | import kotlinx.coroutines.flow.MutableStateFlow
31 | import kotlinx.coroutines.launch
32 | import kotlinx.coroutines.withContext
33 | import okhttp3.MultipartBody
34 | import okhttp3.RequestBody
35 | import okhttp3.RequestBody.Companion.toRequestBody
36 | import okio.IOException
37 | import javax.inject.Inject
38 |
39 |
40 | @AndroidEntryPoint
41 | class UploadFileService : LifecycleService() {
42 |
43 | @Inject
44 | lateinit var uploadUseCases: UploadUseCases
45 |
46 | @Inject
47 | lateinit var localDatastoreUseCases: LocalDatastoreUseCases
48 |
49 | private var isPaused = false
50 | private var isCanceled = false
51 | private var uriOfTheFile: Uri? = null
52 |
53 |
54 | companion object {
55 | val progress = MutableStateFlow(0)
56 | val uploadSpeed = MutableStateFlow(0.0)
57 | val estimatedTimeRemaining = MutableStateFlow(0L)
58 | val eventError = MutableSharedFlow()
59 | }
60 |
61 | override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
62 | when (intent?.action) {
63 | UploadFileServiceActions.START.toString() -> startService(uri = intent.data!!)
64 | UploadFileServiceActions.PAUSE_RESUME.toString() -> if (!isPaused) pauseService() else resumeService()
65 |
66 | UploadFileServiceActions.CANCEL.toString() -> cancelService()
67 | }
68 | return super.onStartCommand(intent, flags, startId)
69 | }
70 |
71 | private fun startService(uri: Uri) {
72 | uriOfTheFile = uri
73 | val contentLength = uri.getFileSize(contentResolver)
74 | val fileName = uri.getFileName(contentResolver)
75 | val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
76 | var uriDetails: UriDetailsUiModel
77 | var currentPosition: Long
78 | var startByte: Long
79 | var endByte: Long
80 | var bytesRead: Int
81 | var contentRange: String
82 | var requestBody: RequestBody
83 | var filePart: MultipartBody.Part
84 | val startTime = System.currentTimeMillis()
85 | lifecycleScope.launch(Dispatchers.IO + retrofitExceptionHandler) {
86 | uriDetails = initializeUriDetails(uri)
87 | startByte = uriDetails.startByte ?: 0
88 | currentPosition = uriDetails.startByte ?: 0
89 | val inputStream = contentResolver.openInputStream(uri) ?: return@launch
90 | withContext(Dispatchers.IO) {
91 | inputStream.skip(startByte)
92 | }
93 | while (withContext(Dispatchers.IO) {
94 | inputStream.read(buffer)
95 | }.also { bytesRead = it } != -1) {
96 | if (isPaused || isCanceled) break
97 | startByte = currentPosition
98 | endByte = (currentPosition + bytesRead - 1)
99 | contentRange = "bytes $startByte-$endByte/$contentLength"
100 | requestBody = buffer.copyOfRange(0, bytesRead).toRequestBody()
101 | filePart = MultipartBody.Part.createFormData(
102 | "file",
103 | fileName,
104 | requestBody
105 | )
106 | uploadUseCases.uploadFileToServerUseCase(
107 | contentRange = contentRange,
108 | fileIdentifier = uriDetails.fileIdentifier!!,
109 | file = filePart
110 | )
111 | currentPosition += bytesRead
112 | progress.value = calculateProgressValue(endByte, contentLength)
113 | uploadSpeed.value = calculateUploadSpeed(endByte, startTime)
114 | estimatedTimeRemaining.value = calculateEstimatedTimeRemaining(
115 | endByte,
116 | contentLength,
117 | uploadSpeed.value
118 | )
119 | updateUriDetailsModel(
120 | uri,
121 | uriDetails.fileIdentifier!!,
122 | endByte,
123 | progress.value
124 | )
125 | startForeground(
126 | NOTIFICATION_ID,
127 | buildNotification(
128 | progress.value,
129 | uploadSpeed.value.toLong(),
130 | estimatedTimeRemaining.value,
131 | isPaused
132 | )
133 | )
134 | }
135 | withContext(Dispatchers.IO) {
136 | inputStream.close()
137 | }
138 | if (!isPaused) {
139 | cancelService()
140 | }
141 | }
142 | }
143 |
144 | private suspend fun initializeUriDetails(uri: Uri): UriDetailsUiModel {
145 | var uriDetails = localDatastoreUseCases.readUriModelDetailsForUploadUseCase(uri.toString())
146 | ?.toUriDetailsUiModel()
147 | if (uriDetails == null) {
148 | localDatastoreUseCases.writeUriModelDetailsForUploadUseCase(
149 | uri.toString(), UriDetailsUiModel(
150 | fileIdentifier = generateUUIDv4().toString(),
151 | startByte = 0,
152 | ).toUriDetailsDomainModel()
153 | )
154 | uriDetails = localDatastoreUseCases.readUriModelDetailsForUploadUseCase(uri.toString())
155 | ?.toUriDetailsUiModel()
156 | } else {
157 | uriDetails.startByte = uriDetails.startByte ?: 0
158 | }
159 | return uriDetails!!
160 | }
161 |
162 | private fun calculateProgressValue(endByte: Long, contentLength: Long) =
163 | (((endByte + 1).toDouble() / contentLength.toDouble()) * 100).toInt()
164 |
165 | private fun calculateEstimatedTimeRemaining(
166 | endByte: Long,
167 | contentLength: Long,
168 | currentSpeed: Double
169 | ): Long {
170 | val remainingBytes = contentLength - (endByte + 1)
171 | return if (currentSpeed > 0) {
172 | (remainingBytes / currentSpeed).toLong()
173 | } else {
174 | -1
175 | }
176 | }
177 |
178 | private fun calculateUploadSpeed(endByte: Long, startTime: Long): Double {
179 | val currentTime = System.currentTimeMillis()
180 | val elapsedTime = (currentTime - startTime) / 1000.0
181 | return if (elapsedTime > 0) {
182 | (endByte + 1) / elapsedTime
183 | } else {
184 | 0.0
185 | }
186 | }
187 |
188 | private suspend fun updateUriDetailsModel(
189 | uri: Uri,
190 | fileIdentifier: String,
191 | endByte: Long,
192 | progress: Int
193 | ) {
194 | localDatastoreUseCases.writeUriModelDetailsForUploadUseCase(
195 | uri.toString(), UriDetailsUiModel(
196 | fileIdentifier = fileIdentifier,
197 | startByte = endByte + 1,
198 | progress = progress
199 | ).toUriDetailsDomainModel()
200 | )
201 | }
202 |
203 | private fun pauseService() {
204 | isPaused = true
205 | startForeground(
206 | NOTIFICATION_ID + 1,
207 | buildNotification(
208 | progress.value,
209 | 0,
210 | -1,
211 | isPaused
212 | )
213 | )
214 | }
215 |
216 | private fun resumeService() {
217 | isPaused = false
218 | startService(uriOfTheFile!!)
219 | }
220 |
221 | private fun cancelService() {
222 | isCanceled = true
223 | lifecycleScope.launch {
224 | localDatastoreUseCases.deleteUriDetailsAboutUploadUseCase(uriOfTheFile.toString())
225 | stopForeground(STOP_FOREGROUND_REMOVE)
226 | stopSelf()
227 | }
228 | }
229 |
230 | private fun getPendingIntent(action: UploadFileServiceActions): PendingIntent {
231 | val intent = Intent(this, UploadFileService::class.java)
232 | intent.action = action.toString()
233 | return PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_IMMUTABLE)
234 | }
235 |
236 | private fun buildNotification(
237 | progress: Int,
238 | uploadSpeed: Long,
239 | estimatedTimeRemaining: Long,
240 | isPaused: Boolean
241 | ): Notification {
242 | val notificationIntent = Intent(this, MainActivity::class.java)
243 | val pendingIntent = PendingIntent.getActivity(
244 | this, 0, notificationIntent,
245 | PendingIntent.FLAG_IMMUTABLE
246 | )
247 | val pauseResumeLabel = if (isPaused) "Resume" else "Pause"
248 | val builder = NotificationCompat.Builder(this, CHANNEL_ID)
249 | .setContentTitle("File Upload")
250 | .setContentIntent(pendingIntent)
251 | .setAutoCancel(false)
252 | .setOngoing(true)
253 | .setSmallIcon(R.drawable.upload_icon)
254 | .setPriority(NotificationCompat.PRIORITY_HIGH)
255 | .addAction(0, pauseResumeLabel, getPendingIntent(UploadFileServiceActions.PAUSE_RESUME))
256 | .addAction(0, "Cancel", getPendingIntent(UploadFileServiceActions.CANCEL))
257 | if (progress < 100) builder.setProgress(100, progress, false)
258 | else builder.setProgress(0, 0, false)
259 |
260 | if (progress < 100) {
261 | builder.setSubText(uploadSpeed.formatSpeed())
262 | if (estimatedTimeRemaining > 0) builder.setContentText(estimatedTimeRemaining.formatTime())
263 | else builder.setSubText("Time remaining: 1 year")
264 | }
265 | return builder.build()
266 | }
267 |
268 | enum class UploadFileServiceActions {
269 | START, PAUSE_RESUME, CANCEL
270 | }
271 |
272 | private val retrofitExceptionHandler = CoroutineExceptionHandler { _, throwable ->
273 | if (throwable is IOException) {
274 | setEventError(RetrofitErrorType.NETWORK_ERROR)
275 | }
276 | }
277 |
278 | private fun setEventError(event: RetrofitErrorType) {
279 | lifecycleScope.launch {
280 | eventError.emit(event)
281 | }
282 | }
283 | }
284 |
--------------------------------------------------------------------------------