├── app
├── .gitignore
├── src
│ ├── main
│ │ ├── res
│ │ │ ├── mipmap-hdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── mipmap-mdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── mipmap-xhdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── mipmap-xxhdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── mipmap-xxxhdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── values
│ │ │ │ ├── colors.xml
│ │ │ │ ├── dimens.xml
│ │ │ │ ├── styles.xml
│ │ │ │ └── strings.xml
│ │ │ ├── drawable-v24
│ │ │ │ └── ic_launcher_foreground.xml
│ │ │ ├── layout
│ │ │ │ ├── activity_main.xml
│ │ │ │ └── layout_download_item.xml
│ │ │ └── drawable
│ │ │ │ └── ic_launcher_background.xml
│ │ ├── java
│ │ │ └── com
│ │ │ │ └── app
│ │ │ │ └── nikhil
│ │ │ │ └── coroutinedownloader
│ │ │ │ ├── ui
│ │ │ │ ├── ViewState.kt
│ │ │ │ ├── base
│ │ │ │ │ ├── ViewModelFactory.kt
│ │ │ │ │ └── BaseActivity.kt
│ │ │ │ └── main
│ │ │ │ │ ├── MainViewModel.kt
│ │ │ │ │ └── MainActivity.kt
│ │ │ │ ├── injection
│ │ │ │ ├── scope
│ │ │ │ │ ├── ActivityScope.kt
│ │ │ │ │ └── ViewModelKey.kt
│ │ │ │ ├── qualifier
│ │ │ │ │ └── IOScope.kt
│ │ │ │ ├── module
│ │ │ │ │ ├── ServiceBindingModule.kt
│ │ │ │ │ ├── ActivityBindingModule.kt
│ │ │ │ │ ├── ViewModelBindingModule.kt
│ │ │ │ │ └── AppModule.kt
│ │ │ │ └── component
│ │ │ │ │ └── AppComponent.kt
│ │ │ │ ├── models
│ │ │ │ ├── DownloadState.kt
│ │ │ │ ├── DownloadItem.kt
│ │ │ │ └── DownloadProgress.kt
│ │ │ │ ├── usecase
│ │ │ │ ├── BaseSuspendUseCase.kt
│ │ │ │ └── DownloadUseCase.kt
│ │ │ │ ├── exceptions
│ │ │ │ ├── FileAlreadyDownloadingException.kt
│ │ │ │ ├── FileExistsException.kt
│ │ │ │ └── UserCancelledJobException.kt
│ │ │ │ ├── utils
│ │ │ │ ├── Constants.kt
│ │ │ │ ├── KotlinExtensions.kt
│ │ │ │ ├── NumberUtils.kt
│ │ │ │ ├── NotificationUtils.kt
│ │ │ │ ├── DownloadItemRecyclerAdapter.kt
│ │ │ │ └── FileUtils.kt
│ │ │ │ ├── database
│ │ │ │ ├── DownloadDatabase.kt
│ │ │ │ ├── DatabaseDAO.kt
│ │ │ │ ├── Converters.kt
│ │ │ │ └── CentralRepository.kt
│ │ │ │ ├── downloadutils
│ │ │ │ ├── DownloadManager.kt
│ │ │ │ ├── DownloadService.kt
│ │ │ │ └── DownloadManagerImpl.kt
│ │ │ │ └── MainApplication.kt
│ │ └── AndroidManifest.xml
│ ├── test
│ │ └── java
│ │ │ └── com
│ │ │ └── app
│ │ │ └── nikhil
│ │ │ └── coroutinedownloader
│ │ │ └── ExampleUnitTest.kt
│ └── androidTest
│ │ └── java
│ │ └── com
│ │ └── app
│ │ └── nikhil
│ │ └── coroutinedownloader
│ │ └── ExampleInstrumentedTest.kt
├── proguard-rules.pro
└── build.gradle
├── settings.gradle
├── images
├── paused.png
└── completed.png
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── .idea
├── encodings.xml
├── vcs.xml
├── codeStyles
│ ├── codeStyleConfig.xml
│ └── Project.xml
├── modules.xml
├── misc.xml
└── runConfigurations.xml
├── README.md
├── gradle.properties
├── .gitignore
├── gradlew.bat
├── gradlew
└── LICENSE
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app'
2 |
--------------------------------------------------------------------------------
/images/paused.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nikhilbansal97/CoroutineDownloader/HEAD/images/paused.png
--------------------------------------------------------------------------------
/images/completed.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nikhilbansal97/CoroutineDownloader/HEAD/images/completed.png
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nikhilbansal97/CoroutineDownloader/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nikhilbansal97/CoroutineDownloader/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nikhilbansal97/CoroutineDownloader/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nikhilbansal97/CoroutineDownloader/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nikhilbansal97/CoroutineDownloader/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/.idea/encodings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nikhilbansal97/CoroutineDownloader/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/java/com/app/nikhil/coroutinedownloader/ui/ViewState.kt:
--------------------------------------------------------------------------------
1 | package com.app.nikhil.coroutinedownloader.ui
2 |
3 | sealed class ViewState {
4 | class Downloading
5 | }
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/java/com/app/nikhil/coroutinedownloader/injection/scope/ActivityScope.kt:
--------------------------------------------------------------------------------
1 | package com.app.nikhil.coroutinedownloader.injection.scope
2 |
3 | import javax.inject.Scope
4 |
5 | @Scope
6 | annotation class ActivityScope
--------------------------------------------------------------------------------
/app/src/main/java/com/app/nikhil/coroutinedownloader/models/DownloadState.kt:
--------------------------------------------------------------------------------
1 | package com.app.nikhil.coroutinedownloader.models
2 |
3 | enum class DownloadState {
4 | PENDING,
5 | PAUSED,
6 | COMPLETED,
7 | DOWNLOADING
8 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/app/nikhil/coroutinedownloader/usecase/BaseSuspendUseCase.kt:
--------------------------------------------------------------------------------
1 | package com.app.nikhil.coroutinedownloader.usecase
2 |
3 | interface BaseSuspendUseCase {
4 | suspend fun perform(param: U): T
5 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/app/nikhil/coroutinedownloader/exceptions/FileAlreadyDownloadingException.kt:
--------------------------------------------------------------------------------
1 | package com.app.nikhil.coroutinedownloader.exceptions
2 |
3 | class FileAlreadyDownloadingException : Exception("File already downloading!")
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #4A6572
4 | #344955
5 | #F9AA33
6 |
7 |
--------------------------------------------------------------------------------
/.idea/codeStyles/codeStyleConfig.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/java/com/app/nikhil/coroutinedownloader/exceptions/FileExistsException.kt:
--------------------------------------------------------------------------------
1 | package com.app.nikhil.coroutinedownloader.exceptions
2 |
3 | class FileExistsException : Exception() {
4 | override val message: String
5 | get() = "File Already Exists"
6 | }
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Mon Aug 16 10:41:07 IST 2021
2 | distributionBase=GRADLE_USER_HOME
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.7.1-bin.zip
4 | distributionPath=wrapper/dists
5 | zipStorePath=wrapper/dists
6 | zipStoreBase=GRADLE_USER_HOME
7 |
--------------------------------------------------------------------------------
/app/src/main/java/com/app/nikhil/coroutinedownloader/injection/qualifier/IOScope.kt:
--------------------------------------------------------------------------------
1 | package com.app.nikhil.coroutinedownloader.injection.qualifier
2 |
3 | import javax.inject.Qualifier
4 | import kotlin.annotation.AnnotationRetention.RUNTIME
5 |
6 | @Retention(RUNTIME)
7 | @Qualifier
8 | annotation class IOScope
--------------------------------------------------------------------------------
/app/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 16dp
4 | 8dp
5 | 12dp
6 | 16sp
7 | 6dp
8 |
--------------------------------------------------------------------------------
/app/src/main/java/com/app/nikhil/coroutinedownloader/utils/Constants.kt:
--------------------------------------------------------------------------------
1 | package com.app.nikhil.coroutinedownloader.utils
2 |
3 | object Constants {
4 | const val REQUEST_CODE_EXTERNAL_PERMISSIONS = 1001
5 | const val ACTION_DOWNLOAD = "ACTION_DOWNLOAD"
6 | const val DATABASE_NAME = "download-items-info-db"
7 | const val DATABASE_VERSION = 1
8 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/app/nikhil/coroutinedownloader/exceptions/UserCancelledJobException.kt:
--------------------------------------------------------------------------------
1 | package com.app.nikhil.coroutinedownloader.exceptions
2 |
3 | import kotlinx.coroutines.CancellationException
4 |
5 | class UserCancelledJobException : CancellationException() {
6 | override val message: String?
7 | get() = "User cancelled the Job"
8 | }
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/.idea/codeStyles/Project.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/java/com/app/nikhil/coroutinedownloader/utils/KotlinExtensions.kt:
--------------------------------------------------------------------------------
1 | package com.app.nikhil.coroutinedownloader.utils
2 |
3 | import android.content.ContentResolver
4 | import android.content.ContentValues
5 | import android.net.Uri
6 | import java.net.URI
7 |
8 | fun Uri.toURI(): URI = URI.create(toString())
9 |
10 | fun ContentResolver.safeInsert(uri: Uri, contentValues: ContentValues): Uri =
11 | insert(uri, contentValues) ?: Uri.EMPTY
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/app/src/main/java/com/app/nikhil/coroutinedownloader/injection/module/ServiceBindingModule.kt:
--------------------------------------------------------------------------------
1 | package com.app.nikhil.coroutinedownloader.injection.module
2 |
3 | import com.app.nikhil.coroutinedownloader.downloadutils.DownloadService
4 | import dagger.Module
5 | import dagger.android.ContributesAndroidInjector
6 |
7 | @Module
8 | abstract class ServiceBindingModule {
9 |
10 | @ContributesAndroidInjector
11 | abstract fun bindDownloadService(): DownloadService
12 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/app/nikhil/coroutinedownloader/injection/scope/ViewModelKey.kt:
--------------------------------------------------------------------------------
1 | package com.app.nikhil.coroutinedownloader.injection.scope
2 |
3 | import androidx.lifecycle.ViewModel
4 | import dagger.MapKey
5 | import kotlin.annotation.AnnotationRetention.RUNTIME
6 | import kotlin.annotation.AnnotationTarget.FUNCTION
7 | import kotlin.reflect.KClass
8 |
9 | @Target(FUNCTION)
10 | @Retention(RUNTIME)
11 | @MapKey
12 | annotation class ViewModelKey (val value: KClass)
--------------------------------------------------------------------------------
/app/src/test/java/com/app/nikhil/coroutinedownloader/ExampleUnitTest.kt:
--------------------------------------------------------------------------------
1 | package com.app.nikhil.coroutinedownloader
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 | }
18 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Coroutine Downloader
3 | Download URL
4 | Download
5 | https://sample-videos.com/video123/mp4/720/big_buck_bunny_720p_30mb.mp4
6 | Downloading
7 | Completed
8 | Pause
9 | Resume
10 |
11 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/app/src/main/java/com/app/nikhil/coroutinedownloader/models/DownloadItem.kt:
--------------------------------------------------------------------------------
1 | package com.app.nikhil.coroutinedownloader.models
2 |
3 | import androidx.room.Entity
4 | import androidx.room.Ignore
5 | import androidx.room.PrimaryKey
6 | import kotlinx.coroutines.channels.ConflatedBroadcastChannel
7 |
8 | @Entity(tableName = "DownloadItemsTable")
9 | data class DownloadItem(
10 | @PrimaryKey
11 | val url: String,
12 | val fileName: String,
13 | var downloadProgress: DownloadProgress = DownloadProgress.EMPTY
14 | ) {
15 | @Ignore
16 | lateinit var channel: ConflatedBroadcastChannel
17 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/app/nikhil/coroutinedownloader/ui/base/ViewModelFactory.kt:
--------------------------------------------------------------------------------
1 | package com.app.nikhil.coroutinedownloader.ui.base
2 |
3 | import androidx.lifecycle.ViewModel
4 | import androidx.lifecycle.ViewModelProvider
5 | import javax.inject.Inject
6 | import javax.inject.Provider
7 |
8 | class ViewModelFactory @Inject constructor(
9 | private val map: Map,
10 | @JvmSuppressWildcards Provider>
11 | ) :
12 | ViewModelProvider.Factory {
13 |
14 | override fun create(modelClass: Class): T {
15 | return map[modelClass]?.get() as T
16 | }
17 | }
--------------------------------------------------------------------------------
/.idea/runConfigurations.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
11 |
12 |
--------------------------------------------------------------------------------
/app/src/main/java/com/app/nikhil/coroutinedownloader/database/DownloadDatabase.kt:
--------------------------------------------------------------------------------
1 | package com.app.nikhil.coroutinedownloader.database
2 |
3 | import androidx.room.Database
4 | import androidx.room.RoomDatabase
5 | import androidx.room.TypeConverters
6 | import com.app.nikhil.coroutinedownloader.models.DownloadItem
7 | import com.app.nikhil.coroutinedownloader.utils.Constants
8 |
9 | @Database(
10 | entities = [DownloadItem::class], version = Constants.DATABASE_VERSION, exportSchema = false
11 | )
12 | @TypeConverters(Converters::class)
13 | abstract class DownloadDatabase : RoomDatabase() {
14 | abstract fun getDao(): DatabaseDAO
15 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/app/nikhil/coroutinedownloader/downloadutils/DownloadManager.kt:
--------------------------------------------------------------------------------
1 | package com.app.nikhil.coroutinedownloader.downloadutils
2 |
3 | import com.app.nikhil.coroutinedownloader.models.DownloadItem
4 | import com.app.nikhil.coroutinedownloader.models.DownloadProgress
5 | import kotlinx.coroutines.channels.BroadcastChannel
6 |
7 | interface DownloadManager {
8 | suspend fun pause(downloadItem: DownloadItem)
9 | suspend fun resumeQueue()
10 | suspend fun pauseQueue()
11 |
12 | fun download(url: String): DownloadItem
13 | fun onProgressChanged(url: String, function: (item: DownloadProgress) -> Unit)
14 | fun disposeDownload(url: String)
15 | fun disposeAll()
16 | fun getChannel(url: String): BroadcastChannel?
17 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/app/nikhil/coroutinedownloader/MainApplication.kt:
--------------------------------------------------------------------------------
1 | package com.app.nikhil.coroutinedownloader
2 |
3 | import com.app.nikhil.coroutinedownloader.injection.component.DaggerAppComponent
4 | import dagger.android.AndroidInjector
5 | import dagger.android.support.DaggerApplication
6 | import timber.log.Timber
7 | import timber.log.Timber.DebugTree
8 |
9 | class MainApplication : DaggerApplication() {
10 |
11 | override fun applicationInjector(): AndroidInjector {
12 | return DaggerAppComponent.builder()
13 | .create(this)
14 | }
15 |
16 | override fun onCreate() {
17 | super.onCreate()
18 |
19 | initTimber()
20 | }
21 |
22 | private fun initTimber() {
23 | if (BuildConfig.DEBUG) {
24 | Timber.plant(DebugTree())
25 | }
26 | }
27 | }
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/app/nikhil/coroutinedownloader/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | package com.app.nikhil.coroutinedownloader
2 |
3 | import androidx.test.InstrumentationRegistry
4 | import androidx.test.runner.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.getTargetContext()
22 | assertEquals("com.app.nikhil.coroutinedownloader", appContext.packageName)
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/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
22 |
--------------------------------------------------------------------------------
/app/src/main/java/com/app/nikhil/coroutinedownloader/models/DownloadProgress.kt:
--------------------------------------------------------------------------------
1 | package com.app.nikhil.coroutinedownloader.models
2 |
3 | import android.net.Uri
4 |
5 | data class DownloadProgress(
6 | var megaBytesDownloaded: String,
7 | var percentage: Int,
8 | var percentageDisplay: String,
9 | var totalMegaBytes: String,
10 | var bytesDownloaded: Long,
11 | var totalBytes: Long,
12 | var state: DownloadState,
13 | var uri: String
14 | ) {
15 | companion object {
16 | val EMPTY: DownloadProgress
17 | get() = DownloadProgress(
18 | megaBytesDownloaded = "0",
19 | percentage = 0,
20 | percentageDisplay = "0",
21 | totalMegaBytes = "0",
22 | bytesDownloaded = 0L,
23 | totalBytes = 0L,
24 | state = DownloadState.PENDING,
25 | uri = Uri.EMPTY.toString()
26 | )
27 | }
28 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/app/nikhil/coroutinedownloader/injection/module/ActivityBindingModule.kt:
--------------------------------------------------------------------------------
1 | package com.app.nikhil.coroutinedownloader.injection.module
2 |
3 | import com.app.nikhil.coroutinedownloader.injection.scope.ActivityScope
4 | import com.app.nikhil.coroutinedownloader.ui.main.MainActivity
5 | import dagger.Binds
6 | import dagger.Module
7 | import dagger.android.ContributesAndroidInjector
8 | import dagger.android.support.DaggerAppCompatActivity
9 |
10 | @Module
11 | abstract class ActivityBindingModule {
12 |
13 | @ActivityScope
14 | @ContributesAndroidInjector(modules = [MainActivityModule::class])
15 | internal abstract fun bindMainActivity(): MainActivity
16 | }
17 |
18 | @Module
19 | abstract class MainActivityModule {
20 |
21 | @Binds
22 | @ActivityScope
23 | abstract fun bindActivity(mainActivity: MainActivity): DaggerAppCompatActivity
24 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/app/nikhil/coroutinedownloader/injection/module/ViewModelBindingModule.kt:
--------------------------------------------------------------------------------
1 | package com.app.nikhil.coroutinedownloader.injection.module
2 |
3 | import androidx.lifecycle.ViewModel
4 | import androidx.lifecycle.ViewModelProvider
5 | import com.app.nikhil.coroutinedownloader.injection.scope.ViewModelKey
6 | import com.app.nikhil.coroutinedownloader.ui.base.ViewModelFactory
7 | import com.app.nikhil.coroutinedownloader.ui.main.MainViewModel
8 | import dagger.Binds
9 | import dagger.Module
10 | import dagger.multibindings.IntoMap
11 |
12 | @Module
13 | abstract class ViewModelBindingModule {
14 |
15 | @Binds
16 | @IntoMap
17 | @ViewModelKey(MainViewModel::class)
18 | abstract fun bindMainViewModel(mainViewModel: MainViewModel): ViewModel
19 |
20 | @Binds
21 | abstract fun bindViewModelFactory(factory: ViewModelFactory): ViewModelProvider.Factory
22 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/app/nikhil/coroutinedownloader/utils/NumberUtils.kt:
--------------------------------------------------------------------------------
1 | package com.app.nikhil.coroutinedownloader.utils
2 |
3 | import java.math.RoundingMode
4 | import java.text.DecimalFormat
5 |
6 | object NumberUtils {
7 |
8 | private const val MEGA_BYTES_MULTIPLIER = 0.000001
9 | private const val DECIMAL_PERCENT_FORMAT = "#.##"
10 | private val percentageFormat =
11 | DecimalFormat(DECIMAL_PERCENT_FORMAT).apply {
12 | roundingMode =
13 | RoundingMode.CEILING
14 | }
15 |
16 | fun getDisplayPercentage(
17 | bytesRead: Long,
18 | totalBytes: Long
19 | ): String = percentageFormat.format((bytesRead.toDouble() / totalBytes.toDouble()) * 100)
20 |
21 | fun getPercentage(
22 | bytesRead: Long,
23 | totalBytes: Long
24 | ): Int = ((bytesRead.toDouble() / totalBytes.toDouble()) * 100).toInt()
25 |
26 | fun convertBytesToMB(bytes: Long): String =
27 | percentageFormat.format(bytes * MEGA_BYTES_MULTIPLIER)
28 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/app/nikhil/coroutinedownloader/database/DatabaseDAO.kt:
--------------------------------------------------------------------------------
1 | package com.app.nikhil.coroutinedownloader.database
2 |
3 | import androidx.lifecycle.LiveData
4 | import androidx.room.Dao
5 | import androidx.room.Insert
6 | import androidx.room.OnConflictStrategy
7 | import androidx.room.Query
8 | import com.app.nikhil.coroutinedownloader.models.DownloadItem
9 |
10 | @Dao
11 | interface DatabaseDAO {
12 |
13 | @Query("SELECT * FROM DownloadItemsTable")
14 | suspend fun getAll(): List
15 |
16 | @Query("SELECT * FROM DownloadItemsTable WHERE url = :downloadUrl")
17 | suspend fun getItem(downloadUrl: String): DownloadItem
18 |
19 | @Insert(onConflict = OnConflictStrategy.REPLACE)
20 | suspend fun insert(downloadItem: DownloadItem)
21 |
22 | @Insert
23 | suspend fun insertAll(downloadItemList: List)
24 |
25 | @Query("SELECT * FROM DownloadItemsTable")
26 | fun getAllItemsLive(): LiveData>
27 | }
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # CoroutineDownloader
2 |
3 | Download Manager written purely in Kotlin. The app uses coroutines and channels to manage the downloading in background and Okio to buffer.
4 |
5 | > 🚧 Contains the basic logic to download the file. The app does not use the `DownloadManager` class hence the notifications are broken. Feel free to pick it up 😛
6 |
7 | ## Screenshot
8 |
9 |
10 |
11 |
12 |
13 | ## License
14 |
15 | Copyright 2019 Nikhil Bansal
16 |
17 | Licensed under the Apache License, Version 2.0 (the "License");
18 | you may not use this file except in compliance with the License.
19 | You may obtain a copy of the License at
20 |
21 | http://www.apache.org/licenses/LICENSE-2.0
22 |
23 | Unless required by applicable law or agreed to in writing, software
24 | distributed under the License is distributed on an "AS IS" BASIS,
25 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
26 | See the License for the specific language governing permissions and
27 | limitations under the License.
28 |
--------------------------------------------------------------------------------
/app/src/main/java/com/app/nikhil/coroutinedownloader/usecase/DownloadUseCase.kt:
--------------------------------------------------------------------------------
1 | package com.app.nikhil.coroutinedownloader.usecase
2 |
3 | import com.app.nikhil.coroutinedownloader.database.CentralRepository
4 | import com.app.nikhil.coroutinedownloader.downloadutils.DownloadManager
5 | import com.app.nikhil.coroutinedownloader.models.DownloadItem
6 | import kotlinx.coroutines.CoroutineScope
7 | import kotlinx.coroutines.Dispatchers
8 | import kotlinx.coroutines.launch
9 | import javax.inject.Inject
10 |
11 | class DownloadUseCase @Inject constructor(
12 | private val downloadManager: DownloadManager,
13 | private val centralRepository: CentralRepository
14 | ) : BaseSuspendUseCase {
15 |
16 | private val downloadScope = CoroutineScope(Dispatchers.IO)
17 |
18 | override suspend fun perform(param: String): DownloadItem {
19 | val item = downloadManager.download(param)
20 | // Launch a separate coroutine since this will start a database transaction which is
21 | // synchronous and hence blocking.
22 | downloadScope.launch { centralRepository.startSavingDownloadProgress(item) }
23 | return item
24 | }
25 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/app/nikhil/coroutinedownloader/database/Converters.kt:
--------------------------------------------------------------------------------
1 | package com.app.nikhil.coroutinedownloader.database
2 |
3 | import androidx.room.TypeConverter
4 | import com.app.nikhil.coroutinedownloader.models.DownloadProgress
5 | import com.app.nikhil.coroutinedownloader.models.DownloadState
6 | import com.google.gson.Gson
7 |
8 | class Converters {
9 |
10 | private val gson = Gson()
11 |
12 | @TypeConverter
13 | fun fromDownloadState(state: DownloadState): Int = state.ordinal
14 |
15 | @TypeConverter
16 | fun toDownloadState(value: Int): DownloadState {
17 | return when (value) {
18 | DownloadState.PENDING.ordinal -> DownloadState.PENDING
19 | DownloadState.DOWNLOADING.ordinal -> DownloadState.DOWNLOADING
20 | DownloadState.COMPLETED.ordinal -> DownloadState.COMPLETED
21 | else -> DownloadState.PAUSED
22 | }
23 | }
24 |
25 | @TypeConverter
26 | fun fromDownloadProgress(progress: DownloadProgress): String {
27 | return gson.toJson(progress)
28 | }
29 |
30 | @TypeConverter
31 | fun toDownloadProgress(progressString: String): DownloadProgress {
32 | return gson.fromJson(progressString, DownloadProgress::class.java)
33 | }
34 | }
--------------------------------------------------------------------------------
/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=-Xmx1536m
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 | # Automatically convert third-party libraries to use AndroidX
19 | android.enableJetifier=true
20 | # Kotlin code style for this project: "official" or "obsolete":
21 | kotlin.code.style=official
22 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Built application files
2 | *.apk
3 | *.ap_
4 |
5 | # Files for the ART/Dalvik VM
6 | *.dex
7 |
8 | # Java class files
9 | *.class
10 |
11 | # Generated files
12 | bin/
13 | gen/
14 | out/
15 |
16 | # Gradle files
17 | .gradle/
18 | build/
19 |
20 | # Local configuration file (sdk path, etc)
21 | local.properties
22 |
23 | # Proguard folder generated by Eclipse
24 | proguard/
25 |
26 | # Log Files
27 | *.log
28 |
29 | # Android Studio Navigation editor temp files
30 | .navigation/
31 |
32 | # Android Studio captures folder
33 | captures/
34 |
35 | # IntelliJ
36 | *.iml
37 | .idea/workspace.xml
38 | .idea/tasks.xml
39 | .idea/gradle.xml
40 | .idea/assetWizardSettings.xml
41 | .idea/dictionaries
42 | .idea/libraries
43 | .idea/caches
44 | .idea/*.xml
45 | .idea/*
46 |
47 | # Keystore files
48 | # Uncomment the following line if you do not want to check your keystore files in.
49 | #*.jks
50 |
51 | # External native build folder generated in Android Studio 2.2 and later
52 | .externalNativeBuild
53 |
54 | # Google Services (e.g. APIs or Firebase)
55 | google-services.json
56 |
57 | # Freeline
58 | freeline.py
59 | freeline/
60 | freeline_project_description.json
61 |
62 | # fastlane
63 | fastlane/report.xml
64 | fastlane/Preview.html
65 | fastlane/screenshots
66 | fastlane/test_output
67 | fastlane/readme.md
68 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 |
9 |
10 |
20 |
22 |
23 |
24 |
25 |
26 |
27 |
29 |
30 |
31 |
--------------------------------------------------------------------------------
/app/src/main/java/com/app/nikhil/coroutinedownloader/injection/component/AppComponent.kt:
--------------------------------------------------------------------------------
1 | package com.app.nikhil.coroutinedownloader.injection.component
2 |
3 | import android.content.Context
4 | import com.app.nikhil.coroutinedownloader.MainApplication
5 | import com.app.nikhil.coroutinedownloader.injection.module.ActivityBindingModule
6 | import com.app.nikhil.coroutinedownloader.injection.module.AppModule
7 | import com.app.nikhil.coroutinedownloader.injection.module.ServiceBindingModule
8 | import com.app.nikhil.coroutinedownloader.injection.module.ViewModelBindingModule
9 | import dagger.BindsInstance
10 | import dagger.Component
11 | import dagger.android.AndroidInjector
12 | import dagger.android.support.AndroidSupportInjectionModule
13 | import javax.inject.Singleton
14 |
15 | @Singleton
16 | @Component(
17 | modules = [
18 | AndroidSupportInjectionModule::class,
19 | AppModule::class,
20 | ViewModelBindingModule::class,
21 | ActivityBindingModule::class,
22 | ServiceBindingModule::class]
23 | )
24 | interface AppComponent : AndroidInjector {
25 |
26 | /*
27 | * Customize the builder generated by the dagger compiler
28 | */
29 | @Component.Builder
30 | abstract class Builder : AndroidInjector.Builder() {
31 | @BindsInstance
32 | abstract fun appContext(context: Context)
33 |
34 | override fun seedInstance(instance: MainApplication) {
35 | appContext(instance.applicationContext)
36 | }
37 | }
38 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/app/nikhil/coroutinedownloader/injection/module/AppModule.kt:
--------------------------------------------------------------------------------
1 | package com.app.nikhil.coroutinedownloader.injection.module
2 |
3 | import android.content.Context
4 | import androidx.room.Room
5 | import com.app.nikhil.coroutinedownloader.database.DownloadDatabase
6 | import com.app.nikhil.coroutinedownloader.downloadutils.DownloadManager
7 | import com.app.nikhil.coroutinedownloader.downloadutils.DownloadManagerImpl
8 | import com.app.nikhil.coroutinedownloader.injection.qualifier.IOScope
9 | import com.app.nikhil.coroutinedownloader.utils.Constants
10 | import com.app.nikhil.coroutinedownloader.utils.FileUtils
11 | import com.app.nikhil.coroutinedownloader.utils.NotificationUtils
12 | import dagger.Module
13 | import dagger.Provides
14 | import kotlinx.coroutines.CoroutineScope
15 | import kotlinx.coroutines.Dispatchers
16 | import okhttp3.OkHttpClient
17 | import javax.inject.Singleton
18 |
19 | @Module
20 | class AppModule {
21 |
22 | @Provides
23 | @Singleton
24 | fun provideFileUtils(context: Context): FileUtils = FileUtils(context)
25 |
26 | @Provides
27 | @Singleton
28 | fun provideOkHttpClient(): OkHttpClient = OkHttpClient()
29 |
30 | @Provides
31 | @Singleton
32 | fun provideDatabase(context: Context): DownloadDatabase {
33 | return Room.databaseBuilder(context, DownloadDatabase::class.java, Constants.DATABASE_NAME).build()
34 | }
35 |
36 | @Provides
37 | @Singleton
38 | fun provideNotificationUtils(context: Context): NotificationUtils {
39 | return NotificationUtils(context)
40 | }
41 |
42 | @Provides
43 | @Singleton
44 | fun provideDownloader(
45 | okHttpClient: OkHttpClient,
46 | fileUtils: FileUtils,
47 | @IOScope scope: CoroutineScope
48 | ): DownloadManager = DownloadManagerImpl(okHttpClient, fileUtils, scope)
49 |
50 | @Provides
51 | @IOScope
52 | fun provideIOCoroutineScope(): CoroutineScope {
53 | return CoroutineScope(Dispatchers.IO)
54 | }
55 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/app/nikhil/coroutinedownloader/utils/NotificationUtils.kt:
--------------------------------------------------------------------------------
1 | package com.app.nikhil.coroutinedownloader.utils
2 |
3 | import android.app.Notification
4 | import android.app.NotificationChannel
5 | import android.app.NotificationManager
6 | import android.content.Context
7 | import android.content.Context.NOTIFICATION_SERVICE
8 | import android.os.Build.VERSION
9 | import android.os.Build.VERSION_CODES
10 | import androidx.core.app.NotificationCompat
11 | import com.app.nikhil.coroutinedownloader.R
12 | import javax.inject.Inject
13 |
14 | class NotificationUtils @Inject constructor(private val context: Context) {
15 |
16 | companion object {
17 | private const val CHANNEL_ID = "CHANNEL-001"
18 | private const val CHANNEL_NAME = "CoroutineDownloader Channel"
19 | }
20 |
21 | private var currentId = 2
22 |
23 | private val manager: NotificationManager by lazy {
24 | context.getSystemService(
25 | NOTIFICATION_SERVICE
26 | ) as NotificationManager
27 | }
28 |
29 | private val builder: NotificationCompat.Builder by lazy {
30 | val builder = NotificationCompat.Builder(context)
31 | .setSmallIcon(R.mipmap.ic_launcher)
32 |
33 | if (VERSION.SDK_INT >= VERSION_CODES.O) {
34 | builder.apply {
35 | setChannelId(CHANNEL_ID)
36 | setOngoing(true)
37 | }
38 | }
39 | return@lazy builder
40 | }
41 |
42 | fun createNotification(
43 | text: String
44 | ): Notification {
45 | builder.setContentText(text)
46 | if (VERSION.SDK_INT >= VERSION_CODES.O) {
47 | manager.createNotificationChannel(
48 | NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT)
49 | )
50 | }
51 | return builder.build()
52 | }
53 |
54 | fun getSimpleBuilder(): NotificationCompat.Builder = builder
55 |
56 | fun showNotification(notification: Notification) {
57 | manager.notify(currentId++, notification)
58 | }
59 | }
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 | apply plugin: 'kotlin-android'
3 | apply plugin: 'kotlin-android-extensions'
4 | apply plugin: 'kotlin-kapt'
5 |
6 | android {
7 | compileSdkVersion 30
8 | buildToolsVersion "30.0.3"
9 | defaultConfig {
10 | applicationId "com.app.nikhil.coroutinedownloader"
11 | minSdkVersion 21
12 | targetSdkVersion 30
13 | versionCode 1
14 | versionName "1.0"
15 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
16 | }
17 | buildTypes {
18 | release {
19 | minifyEnabled false
20 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
21 | }
22 | }
23 | dataBinding {
24 | enabled = true
25 | }
26 | }
27 |
28 | dependencies {
29 | implementation fileTree(dir: 'libs', include: ['*.jar'])
30 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
31 |
32 | implementation coreDeps.appCompat
33 | implementation coreDeps.androidKtxCore
34 | implementation coreDeps.constraintLayout
35 | implementation coreDeps.recyclerView
36 | implementation coreDeps.materialComponents
37 | implementation coreDeps.viewModelLifecycle
38 |
39 | implementation coreDeps.room
40 | implementation coreDeps.roomKtx
41 | kapt coreDeps.roomProcessor
42 |
43 | implementation coreDeps.okio
44 | implementation coreDeps.okhttp
45 | implementation coreDeps.timber
46 | implementation coreDeps.gson
47 |
48 | implementation coreDeps.coroutineCore
49 | implementation coreDeps.coroutineAndroid
50 |
51 | implementation coreDeps.dagger
52 | implementation coreDeps.daggerAndroid
53 | implementation coreDeps.daggerSupport
54 | implementation coreDeps.daggerSupport
55 | kapt coreDeps.daggerAndroidProcessor
56 | kapt coreDeps.daggerProcessor
57 |
58 | testImplementation testDeps.junit
59 | androidTestImplementation testDeps.testRunner
60 | androidTestImplementation testDeps.espressoCore
61 | }
62 |
--------------------------------------------------------------------------------
/app/src/main/java/com/app/nikhil/coroutinedownloader/database/CentralRepository.kt:
--------------------------------------------------------------------------------
1 | package com.app.nikhil.coroutinedownloader.database
2 |
3 | import androidx.lifecycle.LiveData
4 | import com.app.nikhil.coroutinedownloader.models.DownloadItem
5 | import com.app.nikhil.coroutinedownloader.models.DownloadState.PAUSED
6 | import kotlinx.coroutines.Dispatchers
7 | import kotlinx.coroutines.channels.consumeEach
8 | import kotlinx.coroutines.launch
9 | import kotlinx.coroutines.withContext
10 | import timber.log.Timber
11 | import javax.inject.Inject
12 |
13 | class CentralRepository @Inject constructor(private val database: DownloadDatabase) {
14 |
15 | suspend fun getAllDownloadItems(): List {
16 | return withContext(Dispatchers.IO) {
17 | database.getDao().getAll()
18 | }
19 | }
20 |
21 | fun getAllDownloadItemsLive(): LiveData> {
22 | return database.getDao().getAllItemsLive()
23 | }
24 |
25 | suspend fun saveAllDownloadItems(downloadItemList: List) {
26 | withContext(Dispatchers.IO) {
27 | for (item: DownloadItem in downloadItemList) {
28 | item.downloadProgress.state = PAUSED
29 | }
30 | database.getDao().insertAll(downloadItemList)
31 | }
32 | }
33 |
34 | suspend fun saveDownloadItem(item: DownloadItem) {
35 | withContext(Dispatchers.IO) {
36 | database.getDao().insert(item)
37 | }
38 | }
39 |
40 | suspend fun startSavingDownloadProgress(item: DownloadItem) {
41 | withContext(Dispatchers.IO) {
42 | Timber.d("[CDM] Starting a SQLite transaction")
43 | database.runInTransaction {
44 | this.launch {
45 | Timber.d("[CDM] Starting consuming the channel")
46 | item.channel.consumeEach { downloadProgress ->
47 | Timber.d("[CDM] received download progress ${downloadProgress.percentageDisplay}")
48 | database.getDao().insert(item)
49 | }
50 | }
51 | }
52 | }
53 | }
54 | }
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
12 |
13 |
19 |
22 |
25 |
26 |
27 |
28 |
34 |
35 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
11 |
12 |
13 |
20 |
21 |
28 |
29 |
34 |
35 |
36 |
37 |
47 |
48 |
55 |
56 |
57 |
--------------------------------------------------------------------------------
/app/src/main/java/com/app/nikhil/coroutinedownloader/ui/main/MainViewModel.kt:
--------------------------------------------------------------------------------
1 | package com.app.nikhil.coroutinedownloader.ui.main
2 |
3 | import androidx.lifecycle.LiveData
4 | import androidx.lifecycle.MutableLiveData
5 | import androidx.lifecycle.ViewModel
6 | import androidx.lifecycle.viewModelScope
7 | import com.app.nikhil.coroutinedownloader.database.CentralRepository
8 | import com.app.nikhil.coroutinedownloader.models.DownloadItem
9 | import com.app.nikhil.coroutinedownloader.usecase.DownloadUseCase
10 | import kotlinx.coroutines.launch
11 | import timber.log.Timber
12 | import javax.inject.Inject
13 |
14 | class MainViewModel @Inject constructor(
15 | private val centralRepository: CentralRepository,
16 | private val downloadUseCase: DownloadUseCase
17 | ) : ViewModel() {
18 |
19 | private val _downloadItemsListLiveData = MutableLiveData>()
20 | val downloadItemsLiveData: LiveData>
21 | get() = _downloadItemsListLiveData
22 |
23 | private val _downloadItemLiveData = MutableLiveData()
24 | val downloadItemLiveData: LiveData
25 | get() = _downloadItemLiveData
26 |
27 | private val _exceptionLiveData = MutableLiveData()
28 | val exceptionLiveData: LiveData
29 | get() = _exceptionLiveData
30 |
31 | fun getAllDownloadItems() {
32 | viewModelScope.launch {
33 | val downloadItemsList = centralRepository.getAllDownloadItems()
34 | _downloadItemsListLiveData.postValue(downloadItemsList)
35 | }
36 | }
37 |
38 | fun saveDownloadItemsProgress(downloadItemList: List) {
39 | viewModelScope.launch {
40 | try {
41 | centralRepository.saveAllDownloadItems(downloadItemList)
42 | } catch (e: Exception) {
43 | Timber.e(e)
44 | }
45 | }
46 | }
47 |
48 | fun saveDownloadItem(item: DownloadItem) {
49 | viewModelScope.launch {
50 | centralRepository.saveDownloadItem(item)
51 | }
52 | }
53 |
54 | fun download(url: String) {
55 | viewModelScope.launch {
56 | try {
57 | val item = downloadUseCase.perform(url)
58 | Timber.d("[CDM] Received the download item. Sending to UI")
59 | _downloadItemLiveData.postValue(item)
60 | } catch (e: Exception) {
61 | _exceptionLiveData.postValue(e)
62 | }
63 | }
64 | }
65 | }
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/app/src/main/java/com/app/nikhil/coroutinedownloader/downloadutils/DownloadService.kt:
--------------------------------------------------------------------------------
1 | package com.app.nikhil.coroutinedownloader.downloadutils
2 |
3 | import android.content.Intent
4 | import android.os.Binder
5 | import android.os.IBinder
6 | import com.app.nikhil.coroutinedownloader.models.DownloadItem
7 | import com.app.nikhil.coroutinedownloader.utils.NotificationUtils
8 | import dagger.android.DaggerService
9 | import kotlinx.coroutines.CoroutineScope
10 | import kotlinx.coroutines.Dispatchers
11 | import kotlinx.coroutines.cancel
12 | import kotlinx.coroutines.channels.consumeEach
13 | import kotlinx.coroutines.launch
14 | import javax.inject.Inject
15 |
16 | class DownloadService : DaggerService() {
17 |
18 | private val serviceScope by lazy { CoroutineScope(Dispatchers.IO) }
19 | private val mainScope by lazy { CoroutineScope(Dispatchers.Main) }
20 |
21 | companion object {
22 | private const val MAX_PROGRESS = 100
23 | private const val NOTIFICATION_ID = 1
24 | private const val NOTIFICATION_MESSAGE = "Download Manager active."
25 | }
26 |
27 | @Inject
28 | lateinit var downloadManager: DownloadManager
29 | @Inject
30 | lateinit var notificationUtils: NotificationUtils
31 |
32 | override fun onCreate() {
33 | super.onCreate()
34 | startForeground(NOTIFICATION_ID, notificationUtils.createNotification( NOTIFICATION_MESSAGE))
35 | }
36 |
37 | override fun onStartCommand(
38 | intent: Intent?,
39 | flags: Int,
40 | startId: Int
41 | ): Int {
42 | return super.onStartCommand(intent, flags, startId)
43 | }
44 |
45 | override fun onBind(p0: Intent?): IBinder? = null
46 |
47 | fun download(url: String): DownloadItem {
48 | val downloadItem = downloadManager.download(url)
49 | val receiveChannel = downloadItem.channel.openSubscription()
50 | mainScope.launch {
51 | receiveChannel.consumeEach {
52 | if (it.percentage % 20 == 0) {
53 | val builder = notificationUtils.getSimpleBuilder().apply {
54 | setProgress(MAX_PROGRESS, it.percentage, false)
55 | }
56 | if (it.percentage == MAX_PROGRESS) {
57 | builder.setContentTitle("Downloading")
58 | } else {
59 | builder.setContentTitle("Downloaded")
60 | receiveChannel.cancel()
61 | }
62 | notificationUtils.showNotification(builder.build())
63 | }
64 | }
65 | }
66 | return downloadItem
67 | }
68 |
69 | override fun onDestroy() {
70 | downloadManager.disposeAll()
71 | serviceScope.cancel()
72 | super.onDestroy()
73 | }
74 |
75 | inner class DownloadServiceBinder : Binder() {
76 | fun getService(): DownloadService = this@DownloadService
77 | }
78 | }
--------------------------------------------------------------------------------
/app/src/main/res/layout/layout_download_item.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
18 |
19 |
27 |
28 |
37 |
38 |
46 |
47 |
56 |
57 |
--------------------------------------------------------------------------------
/app/src/main/java/com/app/nikhil/coroutinedownloader/ui/main/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package com.app.nikhil.coroutinedownloader.ui.main
2 |
3 | import android.content.Intent
4 | import android.os.Build.VERSION
5 | import android.os.Build.VERSION_CODES
6 | import android.os.Bundle
7 | import androidx.recyclerview.widget.LinearLayoutManager
8 | import com.app.nikhil.coroutinedownloader.R
9 | import com.app.nikhil.coroutinedownloader.databinding.ActivityMainBinding
10 | import com.app.nikhil.coroutinedownloader.downloadutils.DownloadManager
11 | import com.app.nikhil.coroutinedownloader.downloadutils.DownloadService
12 | import com.app.nikhil.coroutinedownloader.exceptions.FileExistsException
13 | import com.app.nikhil.coroutinedownloader.ui.base.BaseActivity
14 | import com.app.nikhil.coroutinedownloader.utils.DownloadItemRecyclerAdapter
15 | import kotlinx.android.synthetic.main.activity_main.*
16 | import timber.log.Timber
17 | import javax.inject.Inject
18 |
19 | class MainActivity : BaseActivity() {
20 |
21 | override fun getViewModelClass(): Class = MainViewModel::class.java
22 |
23 | override fun getLayoutId(): Int = R.layout.activity_main
24 |
25 | private lateinit var downloadService: DownloadService
26 | private lateinit var downloadItemAdapter: DownloadItemRecyclerAdapter
27 |
28 | @Inject
29 | lateinit var downloadManager: DownloadManager
30 |
31 | override fun onCreate(savedInstanceState: Bundle?) {
32 | super.onCreate(savedInstanceState)
33 |
34 | initRecyclerView()
35 | setupListeners()
36 | observeLiveData()
37 | viewModel.getAllDownloadItems()
38 | }
39 |
40 | private fun observeLiveData() {
41 | viewModel.downloadItemsLiveData.observe(this, {
42 | it?.let { items -> downloadItemAdapter.addAll(items) }
43 | })
44 |
45 | viewModel.downloadItemLiveData.observe(this) {
46 | it?.let { item -> downloadItemAdapter.addItem(item) }
47 | }
48 |
49 | viewModel.exceptionLiveData.observe(this) {
50 | it?.message?.let { message -> showMessage(message) }
51 | }
52 | }
53 |
54 | /*
55 | * Start the download service when the app starts.
56 | */
57 | private fun startDownloadService() {
58 | val serviceIntent = Intent(this, DownloadService::class.java)
59 | if (VERSION.SDK_INT >= VERSION_CODES.O) {
60 | startForegroundService(serviceIntent)
61 | } else {
62 | startService(serviceIntent)
63 | }
64 | }
65 |
66 | private fun setupListeners() {
67 | binding.downloadButton.setOnClickListener {
68 | binding.editTextUrl.text?.toString()?.let { url -> viewModel.download(url) }
69 | }
70 | }
71 |
72 | private fun downloadFile(url: String) {
73 | try {
74 | val item = downloadService.download(url)
75 | downloadItemAdapter.addItem(item)
76 | viewModel.saveDownloadItem(item)
77 | } catch (e: FileExistsException) {
78 | showDialog(e.message)
79 | } catch (e: Exception) {
80 | Timber.e(e)
81 | }
82 | }
83 |
84 | private fun initRecyclerView() {
85 | downloadItemAdapter = DownloadItemRecyclerAdapter(arrayListOf(), downloadManager)
86 | downloadItemsRecycler.apply {
87 | adapter = downloadItemAdapter
88 | layoutManager = LinearLayoutManager(this@MainActivity)
89 | }
90 | }
91 | }
92 |
--------------------------------------------------------------------------------
/app/src/main/java/com/app/nikhil/coroutinedownloader/ui/base/BaseActivity.kt:
--------------------------------------------------------------------------------
1 | package com.app.nikhil.coroutinedownloader.ui.base
2 |
3 | import android.content.pm.PackageManager
4 | import android.os.Build.VERSION
5 | import android.os.Build.VERSION_CODES
6 | import android.os.Bundle
7 | import android.os.Environment
8 | import android.widget.Toast
9 | import androidx.appcompat.app.AlertDialog
10 | import androidx.core.app.ActivityCompat
11 | import androidx.databinding.DataBindingUtil
12 | import androidx.databinding.ViewDataBinding
13 | import androidx.databinding.library.baseAdapters.BR
14 | import androidx.lifecycle.ViewModel
15 | import androidx.lifecycle.ViewModelProvider
16 | import com.app.nikhil.coroutinedownloader.utils.Constants.REQUEST_CODE_EXTERNAL_PERMISSIONS
17 | import dagger.android.AndroidInjection
18 | import dagger.android.support.DaggerAppCompatActivity
19 | import javax.inject.Inject
20 |
21 | abstract class BaseActivity : DaggerAppCompatActivity() {
22 |
23 | abstract fun getLayoutId(): Int
24 |
25 | abstract fun getViewModelClass(): Class
26 |
27 | lateinit var binding: B
28 | lateinit var viewModel: VM
29 |
30 | @Inject
31 | lateinit var viewModelFactory: ViewModelProvider.Factory
32 |
33 | override fun onCreate(savedInstanceState: Bundle?) {
34 | super.onCreate(savedInstanceState)
35 | AndroidInjection.inject(this)
36 | initUI()
37 | if (externalStoragePresent()) {
38 | requestStoragePermission()
39 | }
40 | }
41 |
42 | private fun initUI() {
43 | viewModel = ViewModelProvider(this, viewModelFactory).get(getViewModelClass())
44 | binding = DataBindingUtil.setContentView(this, getLayoutId())
45 | binding.setVariable(BR.viewModel, viewModel)
46 | }
47 |
48 | private fun requestStoragePermission() {
49 | /**
50 | * Request for storage permissions only if app is running on Android 9 or lower.
51 | * Starting Android 10, app doesn't need permission to add files to storage which were created by app.
52 | */
53 | if (VERSION.SDK_INT < VERSION_CODES.Q) {
54 | if (VERSION.SDK_INT >= VERSION_CODES.M) {
55 | requestPermissions(
56 | arrayOf(android.Manifest.permission.WRITE_EXTERNAL_STORAGE),
57 | REQUEST_CODE_EXTERNAL_PERMISSIONS
58 | )
59 | } else {
60 | ActivityCompat.requestPermissions(
61 | this,
62 | arrayOf(android.Manifest.permission.WRITE_EXTERNAL_STORAGE),
63 | REQUEST_CODE_EXTERNAL_PERMISSIONS
64 | )
65 | }
66 | }
67 | }
68 |
69 | override fun onRequestPermissionsResult(
70 | requestCode: Int,
71 | permissions: Array,
72 | grantResults: IntArray
73 | ) {
74 | if (requestCode == REQUEST_CODE_EXTERNAL_PERMISSIONS) {
75 | if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
76 | requestStoragePermission()
77 | }
78 | }
79 | super.onRequestPermissionsResult(requestCode, permissions, grantResults)
80 | }
81 |
82 | private fun externalStoragePresent(): Boolean {
83 | return Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED
84 | }
85 |
86 | fun showDialog(msg: String) {
87 | AlertDialog.Builder(this)
88 | .setMessage(msg)
89 | .show()
90 | }
91 |
92 | fun showMessage(msg: String) {
93 | Toast.makeText(this, msg, Toast.LENGTH_SHORT).show()
94 | }
95 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/app/nikhil/coroutinedownloader/utils/DownloadItemRecyclerAdapter.kt:
--------------------------------------------------------------------------------
1 | package com.app.nikhil.coroutinedownloader.utils
2 |
3 | import android.annotation.SuppressLint
4 | import android.view.LayoutInflater
5 | import android.view.View
6 | import android.view.ViewGroup
7 | import androidx.annotation.UiThread
8 | import androidx.appcompat.widget.AppCompatButton
9 | import androidx.recyclerview.widget.RecyclerView
10 | import com.app.nikhil.coroutinedownloader.R.layout
11 | import com.app.nikhil.coroutinedownloader.R.string
12 | import com.app.nikhil.coroutinedownloader.downloadutils.DownloadManager
13 | import com.app.nikhil.coroutinedownloader.models.DownloadItem
14 | import com.app.nikhil.coroutinedownloader.models.DownloadProgress
15 | import com.app.nikhil.coroutinedownloader.models.DownloadState.COMPLETED
16 | import com.app.nikhil.coroutinedownloader.models.DownloadState.PAUSED
17 | import com.app.nikhil.coroutinedownloader.utils.DownloadItemRecyclerAdapter.DownloadItemViewHolder
18 | import kotlinx.android.synthetic.main.layout_download_item.view.*
19 | import kotlinx.coroutines.CoroutineScope
20 | import kotlinx.coroutines.Dispatchers
21 | import kotlinx.coroutines.launch
22 |
23 | class DownloadItemRecyclerAdapter(
24 | private val downloadItems: ArrayList,
25 | private val downloadManager: DownloadManager
26 | ) : RecyclerView.Adapter() {
27 |
28 | private val mainScope = CoroutineScope(Dispatchers.Main)
29 | private val itemMap: MutableMap = mutableMapOf()
30 |
31 | override fun onCreateViewHolder(
32 | parent: ViewGroup,
33 | viewType: Int
34 | ): DownloadItemViewHolder {
35 | return DownloadItemViewHolder(
36 | LayoutInflater.from(parent.context).inflate(
37 | layout.layout_download_item, parent, false
38 | )
39 | )
40 | }
41 |
42 | fun getDownloadProgressList(): List {
43 | return itemMap.values.toList()
44 | }
45 |
46 | override fun getItemCount(): Int = downloadItems.size
47 |
48 | override fun onBindViewHolder(
49 | holder: DownloadItemViewHolder,
50 | position: Int
51 | ) {
52 | holder.bind(downloadItems[position])
53 | }
54 |
55 | fun addItem(downloadItem: DownloadItem) {
56 | downloadItems.add(downloadItem)
57 | itemMap[downloadItem.url] = downloadItem
58 | notifyDataSetChanged()
59 | }
60 |
61 | fun addAll(items: List) {
62 | downloadItems.addAll(items)
63 | for (item: DownloadItem in items) {
64 | itemMap[item.url] = item
65 | }
66 | notifyDataSetChanged()
67 | }
68 |
69 | inner class DownloadItemViewHolder(private val item: View) : RecyclerView.ViewHolder(item) {
70 | fun bind(downloadItem: DownloadItem) {
71 | item.downloadItemName.text = downloadItem.fileName
72 | setData(downloadItem.downloadProgress)
73 | setPauseResumeListener(downloadItem.url)
74 | consumeDownloadProgressChannel(downloadItem.url)
75 | }
76 |
77 | @SuppressLint("SetTextI18n")
78 | private fun setData(downloadProgress: DownloadProgress) {
79 | with(downloadProgress) {
80 | item.downloadItemProgress.text = "$percentageDisplay%"
81 | item.downloadSizeStatus.text =
82 | "${megaBytesDownloaded}MB / ${totalMegaBytes}MB"
83 | item.downloadItemState.text = state.toString()
84 | item.pauseResumeButton.text = when (state) {
85 | PAUSED -> item.context.getText(string.resume)
86 | else -> item.context.getText(string.pause)
87 | }
88 | }
89 | }
90 |
91 | private fun consumeDownloadProgressChannel(url: String) {
92 | downloadManager.onProgressChanged(url) { updateDownloadProgress(url, it) }
93 | }
94 |
95 | @UiThread
96 | private fun updateDownloadProgress(
97 | url: String,
98 | progress: DownloadProgress
99 | ) {
100 | mainScope.launch {
101 | itemMap[url]?.downloadProgress = progress
102 | setData(progress)
103 | if (progress.state == COMPLETED) {
104 | item.pauseResumeButton.isEnabled = false
105 | }
106 | }
107 | }
108 |
109 | private fun setPauseResumeListener(url: String) {
110 | item.pauseResumeButton.setOnClickListener {
111 | (it as AppCompatButton).let { button ->
112 | mainScope.launch {
113 | if (button.text.toString() == it.context.getString(string.pause) && itemMap[url] != null) {
114 | downloadManager.pause(itemMap[url]!!)
115 | button.text = it.context.getString(string.resume)
116 | } else {
117 | button.text = it.context.getString(string.pause)
118 | downloadManager.download(url)
119 | consumeDownloadProgressChannel(url)
120 | }
121 | item.downloadItemState.text = itemMap[url]?.downloadProgress!!.state.toString()
122 | }
123 | }
124 | }
125 | }
126 | }
127 | }
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
10 |
12 |
14 |
16 |
18 |
20 |
22 |
24 |
26 |
28 |
30 |
32 |
34 |
36 |
38 |
40 |
42 |
44 |
46 |
48 |
50 |
52 |
54 |
56 |
58 |
60 |
62 |
64 |
66 |
68 |
70 |
72 |
74 |
75 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn () {
37 | echo "$*"
38 | }
39 |
40 | die () {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save () {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/app/src/main/java/com/app/nikhil/coroutinedownloader/utils/FileUtils.kt:
--------------------------------------------------------------------------------
1 | package com.app.nikhil.coroutinedownloader.utils
2 |
3 | import android.annotation.SuppressLint
4 | import android.content.ContentResolver
5 | import android.content.ContentValues
6 | import android.content.Context
7 | import android.net.Uri
8 | import android.os.Build
9 | import android.provider.MediaStore
10 | import okio.BufferedSink
11 | import okio.buffer
12 | import okio.sink
13 | import timber.log.Timber
14 | import java.io.File
15 | import java.net.URI
16 |
17 | class FileUtils(private val context: Context) {
18 |
19 | companion object {
20 | private const val MIME_TYPE_VIDEO = "video"
21 | private const val MIME_TYPE_AUDIO = "audio"
22 | private const val MIME_TYPE_IMAGE = "image"
23 | }
24 |
25 | private val contentResolver: ContentResolver by lazy { context.contentResolver }
26 |
27 | fun getFilePath(url: String): String {
28 | val fileName = getFileName(url)
29 | val fileExtension = getFileExtension(url)
30 | val externalDir = context.getExternalFilesDir(fileExtension)
31 | return externalDir?.path + fileName
32 | }
33 |
34 | fun getFileUri(url: String, mimeType: String?): Uri? {
35 | return insertIntoAppropriateMediaStore(url, mimeType)
36 | }
37 |
38 | @SuppressLint("InlinedApi")
39 | private fun insertIntoAppropriateMediaStore(url: String, mimeType: String?): Uri? {
40 | return when {
41 | mimeType == null -> {
42 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
43 | val collectionUri = MediaStore.Downloads.EXTERNAL_CONTENT_URI
44 | val contentValues = ContentValues().apply {
45 | put(MediaStore.Downloads.DISPLAY_NAME, getFileName(url))
46 | put(MediaStore.Downloads.IS_PENDING, 1)
47 | }
48 | contentResolver.safeInsert(collectionUri, contentValues)
49 | } else {
50 | val collectionUri = MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
51 | val contentValues = ContentValues().apply {
52 | put(MediaStore.Files.FileColumns.DISPLAY_NAME, getFileName(url))
53 | put(MediaStore.Files.FileColumns.IS_PENDING, 1)
54 | }
55 | contentResolver.safeInsert(collectionUri, contentValues)
56 | }
57 | }
58 | mimeType.contains(MIME_TYPE_VIDEO) -> {
59 | val collectionUri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
60 | MediaStore.Video.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
61 | } else {
62 | MediaStore.Video.Media.EXTERNAL_CONTENT_URI
63 | }
64 | val contentValues = ContentValues().apply {
65 | put(MediaStore.Video.Media.DISPLAY_NAME, getFileName(url))
66 | put(MediaStore.Video.Media.IS_PENDING, 1)
67 | }
68 | val cursor = contentResolver.query(
69 | Uri.parse("$collectionUri"),
70 | arrayOf(MediaStore.Video.VideoColumns.DISPLAY_NAME),
71 | null,
72 | null
73 | )
74 | Timber.d("Got cursor $cursor")
75 | cursor?.let { cursor ->
76 | val nameIndex = cursor.getColumnIndex(MediaStore.Video.VideoColumns.DISPLAY_NAME)
77 | Timber.d("Cursor has nameIndex $nameIndex")
78 | while (cursor.moveToNext()) {
79 | Timber.d("Cursor has next()")
80 | val name = cursor.getString(nameIndex)
81 | Timber.d("Got $name in MediaStore!")
82 | }
83 | Timber.d("Cursor access completed")
84 | }
85 | contentResolver.insert(collectionUri, contentValues)
86 | }
87 | mimeType.contains(MIME_TYPE_IMAGE) -> {
88 | val collectionUri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
89 | MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
90 | } else {
91 | MediaStore.Images.Media.EXTERNAL_CONTENT_URI
92 | }
93 | val contentValues = ContentValues().apply {
94 | put(MediaStore.Images.Media.DISPLAY_NAME, getFileName(url))
95 | put(MediaStore.Images.Media.IS_PENDING, 1)
96 | }
97 | contentResolver.safeInsert(collectionUri, contentValues)
98 | }
99 | mimeType.contains(MIME_TYPE_AUDIO) -> {
100 | val collectionUri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
101 | MediaStore.Audio.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
102 | } else {
103 | MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
104 | }
105 | val contentValues = ContentValues().apply {
106 | put(MediaStore.Audio.Media.DISPLAY_NAME, getFileName(url))
107 | put(MediaStore.Audio.Media.IS_PENDING, 1)
108 | }
109 | contentResolver.safeInsert(collectionUri, contentValues)
110 | }
111 | else -> {
112 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
113 | val collectionUri = MediaStore.Downloads.EXTERNAL_CONTENT_URI
114 | val contentValues = ContentValues().apply {
115 | put(MediaStore.Downloads.DISPLAY_NAME, getFileName(url))
116 | put(MediaStore.Downloads.IS_PENDING, 1)
117 | }
118 | contentResolver.safeInsert(collectionUri, contentValues)
119 | } else {
120 | val collectionUri = MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
121 | val contentValues = ContentValues().apply {
122 | put(MediaStore.Files.FileColumns.DISPLAY_NAME, getFileName(url))
123 | put(MediaStore.Files.FileColumns.IS_PENDING, 1)
124 | }
125 | contentResolver.safeInsert(collectionUri, contentValues)
126 | }
127 | }
128 | }
129 | }
130 |
131 | fun getFileName(url: String): String {
132 | val uri = URI.create(url)
133 | val path = uri.path
134 | val index = path.indexOfLast { it == '/' }
135 | if (index != -1) {
136 | return path.substring(index + 1)
137 | }
138 | return "Noname"
139 | }
140 |
141 | private fun getFileExtension(url: String): String {
142 | val fileName = getFileName(url)
143 | val index = fileName.indexOfLast { it == '.' }
144 | if (index != -1) {
145 | return fileName.substring(index + 1)
146 | }
147 | return ""
148 | }
149 |
150 | fun getFileSize(fileName: String): Long {
151 | val file = File(context.getExternalFilesDir(null), fileName)
152 | return if (file.exists()) file.length() else 0
153 | }
154 |
155 | fun getNewBufferedSink(uri: Uri): BufferedSink? {
156 | return contentResolver.openOutputStream(uri)?.sink()?.buffer()
157 | }
158 |
159 | fun downloadCompleted(uri: String) {
160 | val finalUri = Uri.parse(uri) ?: return
161 | val contentValues: ContentValues = createDownloadCompleteContentValues(finalUri)
162 | contentResolver.update(finalUri, contentValues, null, null)
163 | }
164 |
165 | @SuppressLint("InlinedApi")
166 | private fun createDownloadCompleteContentValues(uri: Uri): ContentValues {
167 | return ContentValues().apply {
168 | put(MediaStore.Video.Media.IS_PENDING, 0)
169 | }
170 | }
171 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/app/nikhil/coroutinedownloader/downloadutils/DownloadManagerImpl.kt:
--------------------------------------------------------------------------------
1 | package com.app.nikhil.coroutinedownloader.downloadutils
2 |
3 | import android.net.Uri
4 | import com.app.nikhil.coroutinedownloader.exceptions.FileAlreadyDownloadingException
5 | import com.app.nikhil.coroutinedownloader.models.DownloadItem
6 | import com.app.nikhil.coroutinedownloader.models.DownloadProgress
7 | import com.app.nikhil.coroutinedownloader.models.DownloadState
8 | import com.app.nikhil.coroutinedownloader.models.DownloadState.*
9 | import com.app.nikhil.coroutinedownloader.utils.FileUtils
10 | import com.app.nikhil.coroutinedownloader.utils.NumberUtils.convertBytesToMB
11 | import com.app.nikhil.coroutinedownloader.utils.NumberUtils.getDisplayPercentage
12 | import com.app.nikhil.coroutinedownloader.utils.NumberUtils.getPercentage
13 | import kotlinx.coroutines.*
14 | import kotlinx.coroutines.channels.BroadcastChannel
15 | import kotlinx.coroutines.channels.ConflatedBroadcastChannel
16 | import kotlinx.coroutines.channels.consumeEach
17 | import okhttp3.OkHttpClient
18 | import okhttp3.Request
19 | import okio.*
20 | import timber.log.Timber
21 | import java.io.File
22 | import javax.inject.Inject
23 | import kotlin.coroutines.coroutineContext
24 |
25 | @ExperimentalCoroutinesApi
26 | class DownloadManagerImpl @Inject constructor(
27 | private val okHttpClient: OkHttpClient,
28 | private val fileUtils: FileUtils,
29 | private val downloadScope: CoroutineScope
30 | ) : DownloadManager {
31 |
32 | private val downloadMap: MutableMap>> =
33 | hashMapOf()
34 |
35 | // Pause the Queue when the service is destroyed.
36 | override suspend fun pauseQueue() {}
37 |
38 | // Resume the Queue when the service is started.
39 | override suspend fun resumeQueue() {
40 | for (url: String in downloadMap.keys) {
41 | download(url)
42 | }
43 | }
44 |
45 | override fun onProgressChanged(
46 | url: String,
47 | function: (item: DownloadProgress) -> Unit
48 | ) {
49 | downloadScope.launch(Dispatchers.IO) {
50 | downloadMap[url]?.second?.consumeEach { progress ->
51 | function(progress)
52 | if (progress.percentage == 100) {
53 | onDownloadCompleted(progress.uri)
54 | }
55 | }
56 | }
57 | }
58 |
59 | private fun onDownloadCompleted(uri: String) {
60 | fileUtils.downloadCompleted(uri)
61 | }
62 |
63 | // Dispose the resources occupied by the downloader and cancel all coroutines.
64 | override fun disposeAll() {}
65 |
66 | override fun disposeDownload(url: String) {
67 | downloadMap[url]?.first?.cancel()
68 | downloadMap[url]?.second?.close()
69 | }
70 |
71 | override fun download(url: String): DownloadItem {
72 | if (alreadyDownloading(url)) {
73 | throw FileAlreadyDownloadingException()
74 | }
75 |
76 | // Create the request
77 | val request = Request.Builder()
78 | .url(url)
79 | .build()
80 |
81 | // Create a DownloadItem
82 | val downloadItem =
83 | DownloadItem(url, fileUtils.getFileName(url)).apply {
84 | channel = ConflatedBroadcastChannel()
85 | }
86 |
87 | try {
88 | /*
89 | * Launch a coroutine that will start the download and post the updates
90 | * to the channel of the DownloadItem for this Url
91 | */
92 | val job = downloadScope.launch { suspendedDownload(request, url, downloadItem.channel) }
93 | // Create an entry in the in-memory map
94 | downloadMap[url] = Pair(job, downloadItem.channel)
95 | } catch (e: Exception) {
96 | throw e
97 | }
98 | return downloadItem
99 | }
100 |
101 | private suspend fun suspendedDownload(
102 | request: Request,
103 | url: String,
104 | channel: BroadcastChannel
105 | ) {
106 | try {
107 | // Create a connection and get the details about the file.
108 | val response = okHttpClient.newCall(request)
109 | .execute()
110 | // Get the file object for the file to be downloaded.
111 | val uri = fileUtils.getFileUri(url, response.header("Content-Type"))
112 | if (uri?.toString().isNullOrEmpty()) {
113 | Timber.e("uri is null, item was not added to MediaStore!")
114 | return
115 | }
116 | // If the body of response is not empty
117 | response.body?.let { body ->
118 | val file: File? = getFileIfExists(uri)
119 | // Create a buffered output stream (BufferedSink) for the file.
120 | val fileBufferedSink: BufferedSink? = when {
121 | file != null -> {
122 | // File exists
123 | return withContext(Dispatchers.IO) {
124 | when {
125 | file.length() != 0L -> file.appendingSink().buffer()
126 | else -> file.sink().buffer()
127 | }
128 | }
129 | }
130 | else -> fileUtils.getNewBufferedSink(uri!!)
131 | }
132 | // Get the buffered input stream (BufferedStream) for the file.
133 | if (fileBufferedSink == null) {
134 | Timber.e("Unable to write to file!")
135 | return
136 | }
137 | val networkBufferedSource = body.source()
138 | bufferedRead(
139 | networkBufferedSource, fileBufferedSink, DEFAULT_BUFFER_SIZE.toLong(),
140 | body.contentLength(), channel, file?.length() ?: 0L, uri
141 | )
142 | }
143 | } catch (e: Exception) {
144 | Timber.e(e)
145 | } finally {
146 | disposeDownload(url)
147 | }
148 | }
149 |
150 | private fun getFileIfExists(uri: Uri?): File? {
151 | var file: File? = null
152 | try {
153 | file = File(uri.toString())
154 | file.sink().close()
155 | } catch (e: Exception) {
156 | // The file doesn't exist
157 | file = null
158 | }
159 | return file
160 | }
161 |
162 | private fun alreadyDownloading(url: String): Boolean {
163 | return downloadMap[url]?.let { !it.first.isCancelled } ?: false
164 | }
165 |
166 | override suspend fun pause(downloadItem: DownloadItem) {
167 | downloadMap[downloadItem.url]?.let { pair ->
168 | pair.first.cancel()
169 | while (!pair.first.isCancelled) { /* Wait for the job to be cancelled. */
170 | }
171 | publishUpdates(pair.second, downloadItem.downloadProgress.apply { this.state = PAUSED })
172 | pair.second.close()
173 | }
174 | }
175 |
176 | override fun getChannel(url: String): BroadcastChannel? {
177 | return downloadMap[url]?.second
178 | }
179 |
180 | /*
181 | * Read from a BufferedSource and write it in BufferedSink
182 | */
183 | private suspend fun bufferedRead(
184 | source: BufferedSource,
185 | sink: BufferedSink,
186 | bufferSize: Long,
187 | totalBytes: Long,
188 | channel: BroadcastChannel,
189 | seek: Long = 0L,
190 | uri: Uri
191 | ) {
192 | var bytesRead = seek
193 | try {
194 | // Skip the no of bytes already downloaded
195 | source.skip(seek)
196 | var noOfBytes = source.read(sink.buffer, bufferSize)
197 | while (noOfBytes != -1L && coroutineContext[Job]?.isActive == true) {
198 | bytesRead += noOfBytes
199 | publishUpdates(channel, bytesRead, totalBytes, DOWNLOADING, uri)
200 | noOfBytes = source.read(sink.buffer, bufferSize)
201 | }
202 | if (bytesRead != totalBytes) {
203 | bytesRead = source.read(sink.buffer, totalBytes - bytesRead)
204 | }
205 | publishUpdates(channel, bytesRead, totalBytes, COMPLETED, uri)
206 | } catch (e: Exception) {
207 | Timber.e(e)
208 | } finally {
209 | source.close()
210 | sink.close()
211 | }
212 | }
213 |
214 | private suspend fun publishUpdates(
215 | channel: BroadcastChannel,
216 | bytesRead: Long,
217 | totalBytes: Long,
218 | downloadState: DownloadState,
219 | uri: Uri
220 | ) {
221 | try {
222 | if (!channel.isClosedForSend) {
223 | channel.send(
224 | DownloadProgress(
225 | megaBytesDownloaded = convertBytesToMB(bytesRead),
226 | percentageDisplay = getDisplayPercentage(bytesRead, totalBytes),
227 | percentage = getPercentage(bytesRead, totalBytes),
228 | totalMegaBytes = convertBytesToMB(totalBytes),
229 | bytesDownloaded = bytesRead,
230 | totalBytes = totalBytes,
231 | state = downloadState,
232 | uri = uri.toString()
233 | )
234 | )
235 | }
236 | } catch (e: Exception) {
237 | Timber.e(e)
238 | }
239 | }
240 |
241 | private suspend fun publishUpdates(
242 | channel: BroadcastChannel,
243 | downloadProgress: DownloadProgress
244 | ) {
245 | if (!channel.isClosedForSend) {
246 | channel.send(downloadProgress)
247 | }
248 | }
249 | }
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------