├── .gitignore
├── .idea
├── .gitignore
├── compiler.xml
├── deploymentTargetDropDown.xml
├── gradle.xml
├── misc.xml
└── vcs.xml
├── README.md
├── app
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── com
│ │ └── p1mankar
│ │ └── filedownloader
│ │ └── ExampleInstrumentedTest.kt
│ ├── main
│ ├── AndroidManifest.xml
│ ├── java
│ │ └── com
│ │ │ └── p1mankar
│ │ │ └── filedownloader
│ │ │ ├── MainActivity.kt
│ │ │ └── MyApplication.kt
│ └── res
│ │ ├── drawable-v24
│ │ └── ic_launcher_foreground.xml
│ │ ├── drawable
│ │ └── ic_launcher_background.xml
│ │ ├── layout
│ │ └── activity_main.xml
│ │ ├── mipmap-anydpi-v26
│ │ ├── ic_launcher.xml
│ │ └── ic_launcher_round.xml
│ │ ├── mipmap-hdpi
│ │ ├── ic_launcher.webp
│ │ └── ic_launcher_round.webp
│ │ ├── mipmap-mdpi
│ │ ├── ic_launcher.webp
│ │ └── ic_launcher_round.webp
│ │ ├── mipmap-xhdpi
│ │ ├── ic_launcher.webp
│ │ └── ic_launcher_round.webp
│ │ ├── mipmap-xxhdpi
│ │ ├── ic_launcher.webp
│ │ └── ic_launcher_round.webp
│ │ ├── mipmap-xxxhdpi
│ │ ├── ic_launcher.webp
│ │ └── ic_launcher_round.webp
│ │ ├── values-night
│ │ └── themes.xml
│ │ ├── values
│ │ ├── colors.xml
│ │ ├── strings.xml
│ │ └── themes.xml
│ │ └── xml
│ │ ├── backup_rules.xml
│ │ └── data_extraction_rules.xml
│ └── test
│ └── java
│ └── com
│ └── p1mankar
│ └── filedownloader
│ └── ExampleUnitTest.kt
├── build.gradle
├── contentDownloader
├── .gitignore
├── build.gradle
├── consumer-rules.pro
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── com
│ │ └── p1mankar
│ │ └── contentdownloader
│ │ └── ExampleInstrumentedTest.kt
│ ├── main
│ ├── AndroidManifest.xml
│ └── java
│ │ └── com
│ │ └── p1mankar
│ │ └── contentdownloader
│ │ └── downloadModule
│ │ ├── http
│ │ ├── DefaultHttpClient.kt
│ │ └── HttpClient.kt
│ │ ├── internal
│ │ ├── DownloadDispatcher.kt
│ │ ├── DownloadRequest.kt
│ │ ├── DownloadRequestQueue.kt
│ │ └── DownloadTask.kt
│ │ └── utils
│ │ ├── Constanst.kt
│ │ ├── Downloader.kt
│ │ ├── DownloaderConfig.kt
│ │ ├── FileDownloadOutputStream.kt
│ │ ├── FileDownloadRandomAccessFile.kt
│ │ ├── Status.kt
│ │ └── Utils.kt
│ └── test
│ └── java
│ └── com
│ └── p1mankar
│ └── contentdownloader
│ └── ExampleUnitTest.kt
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
└── settings.gradle
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/caches
5 | /.idea/libraries
6 | /.idea/modules.xml
7 | /.idea/workspace.xml
8 | /.idea/navEditor.xml
9 | /.idea/assetWizardSettings.xml
10 | .DS_Store
11 | /build
12 | /captures
13 | .externalNativeBuild
14 | .cxx
15 | local.properties
16 |
--------------------------------------------------------------------------------
/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 |
--------------------------------------------------------------------------------
/.idea/compiler.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/deploymentTargetDropDown.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
19 |
20 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # File Downloader
2 | ### A file downloader library for Android with pause and resume support.
3 |
4 |
5 | ### Overview of library
6 | * This library can be used to download any type of file like images, video, pdf, APK etc.
7 | * Supports large file download.
8 | * Supports proper request canceling.
9 | * We can check the status of downloading with the given download ID.
10 | * Many requests can be made in parallel.
11 | * This file downloader library supports pause and resume while downloading a file.
12 | * This downloader library has a simple interface to make download requests.
13 | * This library gives callbacks for everything like onProgress, onCancel, onStart, onError, etc while downloading a file.
14 | * All types of customization are possible.
15 |
16 |
17 |
18 | ## Using Library in your Android application
19 |
20 | Update your settings.gradle file with the following dependency.
21 |
22 | ```groovy
23 | dependencyResolutionManagement {
24 | repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
25 | repositories {
26 | google()
27 | mavenCentral()
28 | maven { url 'https://jitpack.io' } // this one
29 | }
30 | }
31 | ```
32 |
33 | Update your module level build.gradle file with the following dependency.
34 |
35 | ```groovy
36 | dependencies {
37 | implementation 'com.github.pavanmankar:FileDownloader:1.0.0'
38 | }
39 | ```
40 | Do not forget to add internet permission in manifest if already not present
41 |
42 | ```
43 |
44 | ```
45 |
46 | ### Download Request
47 | ```
48 | val request = downloader.newReqBuilder(
49 | url,
50 | dirPath,
51 | fileName,
52 | ).tag(TAG).build()
53 |
54 | downloadId = downloader.enqueue(request,
55 | onStart = {
56 | },
57 | onProgress = {
58 | },
59 | onPause = {
60 | },
61 | onCompleted = {
62 | },
63 | onError = {
64 | }
65 | )
66 | ```
67 |
68 | ### Pause a download request :
69 |
70 | ```kotlin
71 | downloader.pause(downloadId);
72 | ```
73 | ### Resume a download request
74 | ```kotlin
75 | downloader.resume(downloadId);
76 | ```
77 |
78 | ### Cancel a download request
79 | ```kotlin
80 | // Cancel with the download id
81 | downloader.cancel(downloadId);
82 |
83 | //Cancel by using tag
84 | downloader.cancel(TAG);
85 |
86 | // Cancel all the requests
87 | downloader.cancelAll();
88 | ```
89 |
90 | ### License
91 | ```
92 | Copyright (C) 2024 Pavan Mankar
93 |
94 | Licensed under the Apache License, Version 2.0 (the "License");
95 | you may not use this file except in compliance with the License.
96 | You may obtain a copy of the License at
97 |
98 | http://www.apache.org/licenses/LICENSE-2.0
99 |
100 | Unless required by applicable law or agreed to in writing, software
101 | distributed under the License is distributed on an "AS IS" BASIS,
102 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
103 | See the License for the specific language governing permissions and
104 | limitations under the License.
105 | ```
106 |
107 |
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'com.android.application'
3 | id 'org.jetbrains.kotlin.android'
4 | }
5 |
6 | android {
7 | namespace 'com.p1mankar.filedownloader'
8 | compileSdk 34
9 |
10 | defaultConfig {
11 | applicationId "com.p1mankar.filedownloader"
12 | minSdk 21
13 | targetSdk 34
14 | versionCode 1
15 | versionName "1.0"
16 |
17 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
18 | }
19 |
20 | buildTypes {
21 | release {
22 | minifyEnabled false
23 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
24 | }
25 | }
26 | compileOptions {
27 | sourceCompatibility JavaVersion.VERSION_1_8
28 | targetCompatibility JavaVersion.VERSION_1_8
29 | }
30 | kotlinOptions {
31 | jvmTarget = '1.8'
32 | }
33 | buildFeatures {
34 | viewBinding true
35 | }
36 | }
37 |
38 | dependencies {
39 |
40 | implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.5.1")
41 | implementation 'androidx.core:core-ktx:1.7.0'
42 | implementation 'androidx.appcompat:appcompat:1.5.1'
43 | implementation 'com.google.android.material:material:1.7.0'
44 | implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
45 | implementation project(path: ':contentDownloader')
46 | testImplementation 'junit:junit:4.13.2'
47 | androidTestImplementation 'androidx.test.ext:junit:1.1.4'
48 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.0'
49 | }
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/p1mankar/filedownloader/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | package com.p1mankar.filedownloader
2 |
3 | import androidx.test.platform.app.InstrumentationRegistry
4 | import androidx.test.ext.junit.runners.AndroidJUnit4
5 |
6 | import org.junit.Test
7 | import org.junit.runner.RunWith
8 |
9 | import org.junit.Assert.*
10 |
11 | /**
12 | * Instrumented test, which will execute on an Android device.
13 | *
14 | * See [testing documentation](http://d.android.com/tools/testing).
15 | */
16 | @RunWith(AndroidJUnit4::class)
17 | class ExampleInstrumentedTest {
18 | @Test
19 | fun useAppContext() {
20 | // Context of the app under test.
21 | val appContext = InstrumentationRegistry.getInstrumentation().targetContext
22 | assertEquals("com.p1mankar.filedownloader", appContext.packageName)
23 | }
24 | }
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
18 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
30 |
31 |
32 |
33 |
--------------------------------------------------------------------------------
/app/src/main/java/com/p1mankar/filedownloader/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package com.p1mankar.filedownloader
2 |
3 | import android.os.Bundle
4 | import android.os.Environment
5 | import android.util.Log
6 | import android.view.View
7 | import androidx.appcompat.app.AppCompatActivity
8 | import com.library.Downloader
9 | import com.p1mankar.filedownloader.databinding.ActivityMainBinding
10 |
11 | class MainActivity : AppCompatActivity() {
12 |
13 | companion object {
14 | private const val TAG = "MainActivity"
15 | }
16 |
17 | private lateinit var binding: ActivityMainBinding
18 |
19 | lateinit var dirPath: String
20 | lateinit var downloader: Downloader
21 |
22 | override fun onCreate(savedInstanceState: Bundle?) {
23 | super.onCreate(savedInstanceState)
24 | binding = ActivityMainBinding.inflate(layoutInflater)
25 | setContentView(binding.root)
26 |
27 | downloader = (application as MyApplication).downloader
28 | dirPath = Environment.getExternalStorageDirectory().path + "/Download"
29 | setOnClickListener()
30 | }
31 |
32 | private fun setOnClickListener() {
33 | binding.startCancelButton1.setOnClickListener {
34 | var downloadId1 = 0
35 | if (binding.startCancelButton1.text.equals("Start")) {
36 | val request = downloader.newReqBuilder(
37 | "https://sample-videos.com/video123/mp4/720/big_buck_bunny_720p_30mb.mp4",
38 | dirPath,
39 | "bunny.mp4",
40 | ).tag(TAG + "1").build()
41 | downloadId1 = downloader.enqueue(request, onStart = {
42 | binding.status1.text = "Started"
43 | binding.startCancelButton1.text = "Cancel"
44 | Log.d(TAG, "On Start")
45 | }, onProgress = {
46 | binding.status1.text = "In Progress"
47 | binding.progressBar1.progress = it
48 | binding.progressText1.text = "$it%"
49 | Log.d(TAG, it.toString())
50 | }, onPause = {
51 | binding.status1.text = "Paused"
52 | Log.d(TAG, "On Pause")
53 | }, onCompleted = {
54 | binding.status1.text = "Completed"
55 | Log.d(TAG, "On Complete")
56 | binding.startCancelButton1.text = "Completed"
57 | }, onError = {
58 | binding.status1.text = "Error : $it"
59 | binding.resumePauseButton1.visibility = View.GONE
60 | binding.progressBar1.progress = 0
61 | binding.progressText1.text = "0%"
62 | Log.d(TAG, it)
63 | })
64 | } else if (binding.startCancelButton1.text.equals("Cancel")) {
65 | downloader.cancel(TAG + "1")
66 | binding.startCancelButton1.text = "Start"
67 | }
68 |
69 | }
70 |
71 | binding.startCancelButton2.setOnClickListener {
72 | var downloadId2 = 0
73 | if (binding.startCancelButton2.text.equals("Start")) {
74 | val request1 = downloader.newReqBuilder(
75 | "https://media.giphy.com/media/Bk0CW5frw4qfS/giphy.gif",
76 | dirPath,
77 | "docu.gif",
78 | ).tag(TAG + "2").build()
79 | downloadId2 = downloader.enqueue(request1, onStart = {
80 | binding.status2.text = "Started"
81 | binding.startCancelButton2.text = "Cancel"
82 | Log.d(TAG, "On Start")
83 | }, onProgress = {
84 | binding.status2.text = "In Progress"
85 | binding.progressBar2.progress = it
86 | binding.progressText2.text = "$it%"
87 | Log.d(TAG, it.toString())
88 | }, onPause = {
89 | binding.status2.text = "Paused"
90 | Log.d(TAG, "On Pause")
91 | }, onCompleted = {
92 | binding.status2.text = "Completed"
93 | Log.d(TAG, "On Complete")
94 | binding.startCancelButton2.text = "Completed"
95 | }, onError = {
96 | binding.status2.text = "Error : $it"
97 | binding.resumePauseButton2.visibility = View.GONE
98 | binding.progressBar2.progress = 0
99 | binding.progressText2.text = "0%"
100 | Log.d(TAG, it)
101 | })
102 | } else if (binding.startCancelButton2.text.equals("Cancel")) {
103 | downloader.cancel(downloadId2)
104 | binding.startCancelButton2.text = "Start"
105 | }
106 |
107 | }
108 | }
109 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/p1mankar/filedownloader/MyApplication.kt:
--------------------------------------------------------------------------------
1 | package com.p1mankar.filedownloader
2 |
3 | import android.app.Application
4 | import com.library.Downloader
5 |
6 | class MyApplication : Application() {
7 |
8 | lateinit var downloader: Downloader
9 |
10 | override fun onCreate() {
11 | super.onCreate()
12 | downloader = Downloader.create()
13 |
14 | }
15 | }
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
8 |
9 |
15 |
18 |
21 |
22 |
23 |
24 |
30 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
12 |
13 |
14 |
15 |
20 |
21 |
30 |
31 |
40 |
41 |
50 |
51 |
61 |
62 |
70 |
71 |
82 |
83 |
84 |
85 |
86 |
91 |
92 |
101 |
102 |
111 |
112 |
121 |
122 |
132 |
133 |
141 |
142 |
153 |
154 |
159 |
160 |
161 |
162 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/pavanmankar/FileDownloader/9fd6b282803ef8814f4e2672c7d361260b296d68/app/src/main/res/mipmap-hdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/pavanmankar/FileDownloader/9fd6b282803ef8814f4e2672c7d361260b296d68/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/pavanmankar/FileDownloader/9fd6b282803ef8814f4e2672c7d361260b296d68/app/src/main/res/mipmap-mdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/pavanmankar/FileDownloader/9fd6b282803ef8814f4e2672c7d361260b296d68/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/pavanmankar/FileDownloader/9fd6b282803ef8814f4e2672c7d361260b296d68/app/src/main/res/mipmap-xhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/pavanmankar/FileDownloader/9fd6b282803ef8814f4e2672c7d361260b296d68/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/pavanmankar/FileDownloader/9fd6b282803ef8814f4e2672c7d361260b296d68/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/pavanmankar/FileDownloader/9fd6b282803ef8814f4e2672c7d361260b296d68/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/pavanmankar/FileDownloader/9fd6b282803ef8814f4e2672c7d361260b296d68/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/pavanmankar/FileDownloader/9fd6b282803ef8814f4e2672c7d361260b296d68/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/values-night/themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
16 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #FFBB86FC
4 | #FF6200EE
5 | #FF3700B3
6 | #FF03DAC5
7 | #FF018786
8 | #FF000000
9 | #FFFFFFFF
10 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | FileDownloader
3 |
--------------------------------------------------------------------------------
/app/src/main/res/values/themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
16 |
--------------------------------------------------------------------------------
/app/src/main/res/xml/backup_rules.xml:
--------------------------------------------------------------------------------
1 |
8 |
9 |
13 |
--------------------------------------------------------------------------------
/app/src/main/res/xml/data_extraction_rules.xml:
--------------------------------------------------------------------------------
1 |
6 |
7 |
8 |
12 |
13 |
19 |
--------------------------------------------------------------------------------
/app/src/test/java/com/p1mankar/filedownloader/ExampleUnitTest.kt:
--------------------------------------------------------------------------------
1 | package com.p1mankar.filedownloader
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 | }
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 | plugins {
3 | id 'com.android.application' version '7.3.0' apply false
4 | id 'com.android.library' version '7.3.0' apply false
5 | id 'org.jetbrains.kotlin.android' version '1.7.10' apply false
6 | }
--------------------------------------------------------------------------------
/contentDownloader/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/contentDownloader/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'com.android.library'
3 | id 'org.jetbrains.kotlin.android'
4 | }
5 |
6 | android {
7 | namespace 'com.p1mankar.contentdownloader'
8 | compileSdk 32
9 |
10 | defaultConfig {
11 | minSdk 21
12 | targetSdk 32
13 |
14 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
15 | consumerProguardFiles "consumer-rules.pro"
16 | }
17 |
18 | buildTypes {
19 | release {
20 | minifyEnabled false
21 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
22 | }
23 | }
24 | compileOptions {
25 | sourceCompatibility JavaVersion.VERSION_1_8
26 | targetCompatibility JavaVersion.VERSION_1_8
27 | }
28 | kotlinOptions {
29 | jvmTarget = '1.8'
30 | }
31 | }
32 |
33 | dependencies {
34 |
35 | implementation 'androidx.core:core-ktx:1.7.0'
36 | implementation 'androidx.appcompat:appcompat:1.6.1'
37 | implementation 'com.google.android.material:material:1.10.0'
38 | testImplementation 'junit:junit:4.13.2'
39 | androidTestImplementation 'androidx.test.ext:junit:1.1.5'
40 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
41 | }
--------------------------------------------------------------------------------
/contentDownloader/consumer-rules.pro:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/pavanmankar/FileDownloader/9fd6b282803ef8814f4e2672c7d361260b296d68/contentDownloader/consumer-rules.pro
--------------------------------------------------------------------------------
/contentDownloader/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
--------------------------------------------------------------------------------
/contentDownloader/src/androidTest/java/com/p1mankar/contentdownloader/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | package com.p1mankar.contentdownloader
2 |
3 | import androidx.test.platform.app.InstrumentationRegistry
4 | import androidx.test.ext.junit.runners.AndroidJUnit4
5 |
6 | import org.junit.Test
7 | import org.junit.runner.RunWith
8 |
9 | import org.junit.Assert.*
10 |
11 | /**
12 | * Instrumented test, which will execute on an Android device.
13 | *
14 | * See [testing documentation](http://d.android.com/tools/testing).
15 | */
16 | @RunWith(AndroidJUnit4::class)
17 | class ExampleInstrumentedTest {
18 | @Test
19 | fun useAppContext() {
20 | // Context of the app under test.
21 | val appContext = InstrumentationRegistry.getInstrumentation().targetContext
22 | assertEquals("com.p1mankar.contentdownloader.test", appContext.packageName)
23 | }
24 | }
--------------------------------------------------------------------------------
/contentDownloader/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/contentDownloader/src/main/java/com/p1mankar/contentdownloader/downloadModule/http/DefaultHttpClient.kt:
--------------------------------------------------------------------------------
1 | package com.p1mankar.filedownloader.downloadModule.http
2 |
3 | import com.library.httpclient.HttpClient
4 | import com.p1mankar.filedownloader.downloadModule.internal.DownloadRequest
5 | import com.p1mankar.filedownloader.downloadModule.utils.Constants
6 | import java.io.IOException
7 | import java.io.InputStream
8 | import java.net.HttpURLConnection
9 | import java.net.URL
10 | import java.net.URLConnection
11 | import java.util.Locale
12 |
13 |
14 | class DefaultHttpClient : HttpClient {
15 | private var connection: URLConnection? = null
16 | override fun clone(): HttpClient {
17 | return DefaultHttpClient()
18 | }
19 |
20 | @Throws(IOException::class)
21 | override fun connect(req: DownloadRequest) {
22 | val range: String = java.lang.String.format(
23 | Locale.ENGLISH,
24 | "bytes=%d-", req.downloadedBytes
25 | )
26 |
27 | connection = URL(req.url).openConnection()
28 | connection?.let {
29 | it.readTimeout = req.readTimeOut
30 | it.connectTimeout = req.connectTimeOut
31 |
32 | it.addRequestProperty(Constants.RANGE, range)
33 | addHeaders(req)
34 | it.connect()
35 | }
36 | }
37 |
38 | @Throws(IOException::class)
39 | override fun getResponseCode(): Int {
40 | var responseCode = 0
41 | if (connection is HttpURLConnection) {
42 | responseCode = (connection as HttpURLConnection).responseCode
43 | }
44 | return responseCode
45 | }
46 |
47 | @Throws(IOException::class)
48 | override fun getInputStream(): InputStream? {
49 | return connection?.getInputStream()
50 | }
51 |
52 | override fun getContentLength(): Long {
53 | val length: String? = connection?.getHeaderField("Content-Length")
54 | return length?.toLong() ?: -1
55 | }
56 |
57 | override fun getResponseHeader(name: String): String {
58 | return connection?.getHeaderField(name) ?: ""
59 | }
60 |
61 | override fun close() {
62 | // no operation
63 | }
64 |
65 | override fun getHeaderFields(): Map> {
66 | return connection?.headerFields ?: emptyMap()
67 | }
68 |
69 | override fun getErrorStream(): InputStream? {
70 | return if (connection is HttpURLConnection) {
71 | (connection as HttpURLConnection).errorStream
72 | } else null
73 | }
74 |
75 | private fun addHeaders(req: DownloadRequest) {
76 | val headers: HashMap>? = req.headers
77 | if (headers != null) {
78 | val entries: Set>> = headers.entries
79 | for ((name, list) in entries) {
80 | for (value in list) {
81 | connection?.addRequestProperty(name, value)
82 | }
83 | }
84 | }
85 | }
86 | }
--------------------------------------------------------------------------------
/contentDownloader/src/main/java/com/p1mankar/contentdownloader/downloadModule/http/HttpClient.kt:
--------------------------------------------------------------------------------
1 | package com.library.httpclient
2 |
3 | import com.p1mankar.filedownloader.downloadModule.internal.DownloadRequest
4 | import java.io.IOException
5 | import java.io.InputStream
6 |
7 | interface HttpClient : Cloneable{
8 |
9 |
10 | fun getContentLength(): Long
11 |
12 | fun getHeaderFields(): Map>
13 |
14 | @Throws(IOException::class)
15 | fun getResponseCode(): Int
16 |
17 | @Throws(IOException::class)
18 | fun getInputStream(): InputStream?
19 |
20 | fun getErrorStream(): InputStream?
21 |
22 | public override fun clone(): HttpClient
23 |
24 | @Throws(IOException::class)
25 | fun connect(req: DownloadRequest)
26 |
27 | fun getResponseHeader(name: String): String
28 |
29 | fun close()
30 | }
--------------------------------------------------------------------------------
/contentDownloader/src/main/java/com/p1mankar/contentdownloader/downloadModule/internal/DownloadDispatcher.kt:
--------------------------------------------------------------------------------
1 | package com.library.internal
2 |
3 | import com.library.httpclient.HttpClient
4 | import com.p1mankar.filedownloader.downloadModule.internal.DownloadRequest
5 | import com.p1mankar.filedownloader.downloadModule.utils.Status
6 | import kotlinx.coroutines.CoroutineScope
7 | import kotlinx.coroutines.Dispatchers
8 | import kotlinx.coroutines.SupervisorJob
9 | import kotlinx.coroutines.cancel
10 | import kotlinx.coroutines.launch
11 |
12 | class DownloadDispatcher(private val httpClient: HttpClient) {
13 |
14 | private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
15 |
16 | fun enqueue(req: DownloadRequest): Int {
17 | val job = scope.launch {
18 | execute(req)
19 | }
20 | req.job = job
21 | return req.downloadId
22 | }
23 |
24 | private suspend fun execute(request: DownloadRequest) {
25 | DownloadTask(request, httpClient).run(
26 | onStart = {
27 | executeOnMainThread { request.onStart() }
28 | },
29 | onProgress = {
30 | executeOnMainThread { request.onProgress(it) }
31 | },
32 | onPause = {
33 | executeOnMainThread { request.onPause() }
34 | },
35 | onCompleted = {
36 | executeOnMainThread { request.onCompleted() }
37 | },
38 | onError = {
39 | executeOnMainThread { request.onError(it) }
40 | }
41 | )
42 | }
43 |
44 | private fun executeOnMainThread(block: () -> Unit) {
45 | scope.launch {
46 | block()
47 | }
48 | }
49 |
50 | fun cancel(req: DownloadRequest) {
51 | req.status = Status.CANCELLED
52 | req.job.cancel()
53 | }
54 |
55 | fun cancelAll() {
56 | scope.cancel()
57 | }
58 |
59 | }
--------------------------------------------------------------------------------
/contentDownloader/src/main/java/com/p1mankar/contentdownloader/downloadModule/internal/DownloadRequest.kt:
--------------------------------------------------------------------------------
1 | package com.p1mankar.filedownloader.downloadModule.internal
2 |
3 | import com.p1mankar.filedownloader.downloadModule.utils.Status
4 | import com.p1mankar.filedownloader.downloadModule.utils.getUniqueId
5 | import kotlinx.coroutines.Job
6 |
7 |
8 | class DownloadRequest private constructor(
9 | internal var url: String,
10 | internal val tag: String?,
11 | internal val dirPath: String,
12 | internal val downloadId: Int,
13 | internal val fileName: String,
14 | internal var readTimeOut: Int,
15 | internal var connectTimeOut: Int,
16 | internal var status: Status = Status.UNKNOWN,
17 | internal val headers: HashMap>?,
18 | ) {
19 |
20 | internal var totalBytes: Long = 0
21 | internal var downloadedBytes: Long = 0
22 | internal lateinit var job: Job
23 | internal lateinit var onStart: () -> Unit
24 | internal lateinit var onProgress: (value: Int) -> Unit
25 | internal lateinit var onPause: () -> Unit
26 | internal lateinit var onCompleted: () -> Unit
27 | internal lateinit var onError: (error: String) -> Unit
28 |
29 | data class Builder(
30 | private val url: String,
31 | private val dirPath: String,
32 | private val fileName: String
33 | ) {
34 |
35 | private var tag: String? = null
36 | private var readTimeOut: Int = 0
37 | private var connectTimeOut: Int = 0
38 | private var headers: HashMap>? = null
39 |
40 | fun tag(tag: String) = apply {
41 | this.tag = tag
42 | }
43 |
44 | fun readTimeout(timeout: Int) = apply {
45 | this.readTimeOut = timeout
46 | }
47 |
48 | fun connectTimeout(timeout: Int) = apply {
49 | this.connectTimeOut = timeout
50 | }
51 |
52 | fun headers(headers: HashMap>) = apply {
53 | this.headers = headers
54 | }
55 |
56 | fun build(): DownloadRequest {
57 | return DownloadRequest(
58 | url = url,
59 | tag = tag,
60 | dirPath = dirPath,
61 | downloadId = getUniqueId(url, dirPath, fileName),
62 | fileName = fileName,
63 | readTimeOut = readTimeOut,
64 | connectTimeOut = connectTimeOut,
65 | headers = headers,
66 | )
67 | }
68 | }
69 |
70 | }
--------------------------------------------------------------------------------
/contentDownloader/src/main/java/com/p1mankar/contentdownloader/downloadModule/internal/DownloadRequestQueue.kt:
--------------------------------------------------------------------------------
1 | package com.library.internal
2 |
3 | import com.p1mankar.filedownloader.downloadModule.internal.DownloadRequest
4 |
5 | class DownloadRequestQueue(private val dispatcher: DownloadDispatcher) {
6 |
7 | private val idRequestMap: HashMap = hashMapOf()
8 |
9 | fun enqueue(request: DownloadRequest): Int {
10 | idRequestMap[request.downloadId] = request
11 | return dispatcher.enqueue(request)
12 | }
13 |
14 | fun pause(id: Int) {
15 | idRequestMap[id]?.let {
16 | dispatcher.cancel(it)
17 | }
18 | }
19 |
20 | fun resume(id: Int) {
21 | idRequestMap[id]?.let {
22 | dispatcher.enqueue(it)
23 | }
24 | }
25 |
26 | fun cancel(id: Int) {
27 | idRequestMap[id]?.let {
28 | dispatcher.cancel(it)
29 | }
30 | idRequestMap.remove(id)
31 | }
32 |
33 | fun cancel(tag: String) {
34 | val requestsWithTag = idRequestMap.values.filter {
35 | it.tag == tag
36 | }
37 | for (req in requestsWithTag) {
38 | cancel(req.downloadId)
39 | }
40 | }
41 |
42 | fun cancelAll() {
43 | idRequestMap.clear()
44 | dispatcher.cancelAll()
45 | }
46 |
47 | }
--------------------------------------------------------------------------------
/contentDownloader/src/main/java/com/p1mankar/contentdownloader/downloadModule/internal/DownloadTask.kt:
--------------------------------------------------------------------------------
1 | package com.library.internal
2 |
3 | import com.library.httpclient.HttpClient
4 | import com.p1mankar.filedownloader.downloadModule.internal.DownloadRequest
5 | import com.p1mankar.filedownloader.downloadModule.utils.*
6 | import kotlinx.coroutines.CancellationException
7 | import kotlinx.coroutines.Dispatchers
8 | import kotlinx.coroutines.withContext
9 | import java.io.File
10 | import java.io.IOException
11 | import java.io.InputStream
12 |
13 | class DownloadTask(private val req: DownloadRequest, private val httpClient: HttpClient) {
14 |
15 | private var responseCode = 0
16 | private var totalBytes: Long = 0
17 | private var inputStream: InputStream? = null
18 | private lateinit var outputStream: FileDownloadOutputStream
19 |
20 | private var tempPath: String = ""
21 | private var isResumeSupported = true
22 |
23 |
24 | companion object {
25 | private const val TIME_GAP_FOR_SYNC: Long = 2000
26 | private const val MIN_BYTES_FOR_SYNC: Long = 65536
27 | private const val BUFFER_SIZE = 1024 * 4
28 | }
29 |
30 | suspend fun run(
31 | onStart: () -> Unit = {},
32 | onProgress: (value: Int) -> Unit = { _ -> },
33 | onPause: () -> Unit = {},
34 | onCompleted: () -> Unit = {},
35 | onError: (error: String) -> Unit = { _ -> }
36 | ) {
37 | withContext(Dispatchers.IO) {
38 | try {
39 |
40 | tempPath = getTempPath(req.dirPath, req.fileName)
41 | var file = File(tempPath)
42 |
43 | req.status = Status.RUNNING
44 |
45 | onStart()
46 |
47 | httpClient.connect(req)
48 |
49 | responseCode = httpClient.getResponseCode()
50 |
51 | totalBytes = req.totalBytes
52 |
53 |
54 | if (totalBytes == 0L) {
55 | totalBytes = httpClient.getContentLength()
56 | req.totalBytes = (totalBytes)
57 | }
58 |
59 | inputStream = httpClient.getInputStream()
60 | if (inputStream == null) {
61 | return@withContext
62 | }
63 |
64 | val buff = ByteArray(BUFFER_SIZE)
65 |
66 | if (!file.exists()) {
67 | val parentFile = file.parentFile
68 | if (parentFile != null && !parentFile.exists()) {
69 | if (parentFile.mkdirs()) {
70 | file.createNewFile()
71 | }
72 | } else {
73 | file.createNewFile()
74 | }
75 | }
76 |
77 | this@DownloadTask.outputStream = FileDownloadRandomAccessFile.create(file)
78 |
79 | do {
80 | val byteCount = inputStream!!.read(buff, 0, BUFFER_SIZE)
81 | if (byteCount == -1) {
82 | break
83 | }
84 | if (req.status === Status.CANCELLED) {
85 | deleteTempFile()
86 | onError("Cancelled")
87 | return@withContext
88 | }
89 | outputStream.write(buff, 0, byteCount)
90 | req.downloadedBytes = req.downloadedBytes + byteCount
91 |
92 | var progress = 0
93 | if (totalBytes > 0) {
94 | progress = ((req.downloadedBytes * 100) / totalBytes).toInt()
95 | }
96 | onProgress(progress)
97 | } while (true)
98 |
99 | val path = getPath(req.dirPath, req.fileName)
100 | renameFileName(tempPath, path)
101 | onCompleted()
102 | req.status = Status.COMPLETED
103 | return@withContext
104 | } catch (e: CancellationException) {
105 | deleteTempFile()
106 | req.status = Status.FAILED
107 | onError(e.toString())
108 | return@withContext
109 | } catch (e: Exception) {
110 | if (!isResumeSupported) {
111 | deleteTempFile()
112 | }
113 | req.status = Status.FAILED
114 | onError(e.toString())
115 | return@withContext
116 | } finally {
117 | closeAllSafely()
118 | }
119 | }
120 | }
121 |
122 | private fun deleteTempFile(): Boolean {
123 | val file = File(tempPath)
124 | if (file.exists()) {
125 | return file.delete()
126 | }
127 | return false
128 | }
129 |
130 | private suspend fun closeAllSafely() {
131 |
132 | try {
133 | httpClient.close()
134 | } catch (e: Exception) {
135 | e.printStackTrace()
136 | }
137 |
138 | try {
139 | inputStream.let { it?.close() }
140 | } catch (e: IOException) {
141 | e.printStackTrace()
142 | }
143 |
144 | try {
145 | if (::outputStream.isInitialized) {
146 | outputStream.close()
147 | }
148 | } catch (e: IOException) {
149 | e.printStackTrace()
150 | }
151 |
152 | }
153 |
154 |
155 | }
--------------------------------------------------------------------------------
/contentDownloader/src/main/java/com/p1mankar/contentdownloader/downloadModule/utils/Constanst.kt:
--------------------------------------------------------------------------------
1 | package com.p1mankar.filedownloader.downloadModule.utils
2 |
3 | object Constants {
4 | const val DEFAULT_READ_TIMEOUT_MILLS = 20000
5 | const val DEFAULT_CONNECT_TIMEOUT_MILLS = 20000
6 | const val RANGE = "Range"
7 | }
--------------------------------------------------------------------------------
/contentDownloader/src/main/java/com/p1mankar/contentdownloader/downloadModule/utils/Downloader.kt:
--------------------------------------------------------------------------------
1 | package com.library
2 |
3 | import com.library.internal.DownloadDispatcher
4 | import com.library.internal.DownloadRequestQueue
5 | import com.p1mankar.filedownloader.downloadModule.internal.DownloadRequest
6 |
7 | class Downloader private constructor(private val config: DownloaderConfig) {
8 |
9 | companion object {
10 | fun create(config: DownloaderConfig = DownloaderConfig()): Downloader {
11 | return Downloader(config)
12 | }
13 | }
14 |
15 | private val reqQueue = DownloadRequestQueue(DownloadDispatcher(config.httpClient))
16 |
17 | fun newReqBuilder(url: String, dirPath: String, fileName: String): DownloadRequest.Builder {
18 | return DownloadRequest.Builder(url, dirPath, fileName).readTimeout(config.readTimeOut)
19 | .connectTimeout(config.connectTimeOut)
20 | }
21 |
22 | fun enqueue(
23 | req: DownloadRequest,
24 | onStart: () -> Unit = {},
25 | onProgress: (value: Int) -> Unit = { _ -> },
26 | onPause: () -> Unit = {},
27 | onCompleted: () -> Unit = {},
28 | onError: (error: String) -> Unit = { _ -> }
29 | ): Int {
30 | req.onStart = onStart
31 | req.onProgress = onProgress
32 | req.onPause = onPause
33 | req.onCompleted = onCompleted
34 | req.onError = onError
35 | return reqQueue.enqueue(req)
36 | }
37 |
38 | fun pause(id: Int) {
39 | reqQueue.pause(id)
40 | }
41 |
42 | fun resume(id: Int) {
43 | reqQueue.resume(id)
44 | }
45 |
46 | fun cancel(id: Int) {
47 | reqQueue.cancel(id)
48 | }
49 |
50 | fun cancel(tag: String) {
51 | reqQueue.cancel(tag)
52 | }
53 |
54 | fun cancelAll() {
55 | reqQueue.cancelAll()
56 | }
57 |
58 | }
--------------------------------------------------------------------------------
/contentDownloader/src/main/java/com/p1mankar/contentdownloader/downloadModule/utils/DownloaderConfig.kt:
--------------------------------------------------------------------------------
1 | package com.library
2 |
3 | import com.library.httpclient.HttpClient
4 | import com.p1mankar.filedownloader.downloadModule.http.DefaultHttpClient
5 | import com.p1mankar.filedownloader.downloadModule.utils.Constants
6 |
7 | data class DownloaderConfig(
8 | val httpClient: HttpClient = DefaultHttpClient(),
9 | val connectTimeOut: Int = Constants.DEFAULT_CONNECT_TIMEOUT_MILLS,
10 | val readTimeOut: Int = Constants.DEFAULT_READ_TIMEOUT_MILLS
11 | )
--------------------------------------------------------------------------------
/contentDownloader/src/main/java/com/p1mankar/contentdownloader/downloadModule/utils/FileDownloadOutputStream.kt:
--------------------------------------------------------------------------------
1 | package com.p1mankar.filedownloader.downloadModule.utils
2 |
3 | import java.io.IOException
4 |
5 | interface FileDownloadOutputStream {
6 | /**
7 | * Writes `len` bytes from the specified byte array
8 | * starting at offset `off` to this file.
9 | */
10 | @Throws(IOException::class)
11 | fun write(b: ByteArray?, off: Int, len: Int)
12 |
13 | /**
14 | * Flush all buffer to system and force all system buffers to synchronize with the underlying
15 | * device.
16 | */
17 | @Throws(IOException::class)
18 | fun flushAndSync()
19 |
20 | /**
21 | * Closes this output stream and releases any system resources associated with this stream. The
22 | * general contract of `close` is that it closes the output stream. A closed stream
23 | * cannot perform output operations and cannot be reopened.
24 | */
25 | @Throws(IOException::class)
26 | fun close()
27 |
28 | /**
29 | * Sets the file-pointer offset, measured from the beginning of this file, at which the next
30 | * read or write occurs. The offset may be set beyond the end of the file.
31 | */
32 | @Throws(IOException::class, IllegalAccessException::class)
33 | fun seek(offset: Long)
34 |
35 | /**
36 | * Sets the length of this file.
37 | */
38 | @Throws(IOException::class, IllegalAccessException::class)
39 | fun setLength(newLength: Long)
40 | }
--------------------------------------------------------------------------------
/contentDownloader/src/main/java/com/p1mankar/contentdownloader/downloadModule/utils/FileDownloadRandomAccessFile.kt:
--------------------------------------------------------------------------------
1 | package com.p1mankar.filedownloader.downloadModule.utils
2 |
3 | import java.io.*
4 |
5 | class FileDownloadRandomAccessFile constructor(file: File) : FileDownloadOutputStream {
6 | private val out: BufferedOutputStream
7 | private val fd: FileDescriptor
8 | private val randomAccess: RandomAccessFile
9 |
10 | init {
11 | randomAccess = RandomAccessFile(file, "rw")
12 | fd = randomAccess.fd
13 | out = BufferedOutputStream(FileOutputStream(randomAccess.fd))
14 | }
15 |
16 | @Throws(IOException::class)
17 | override fun write(b: ByteArray?, off: Int, len: Int) {
18 | out.write(b, off, len)
19 | }
20 |
21 | @Throws(IOException::class)
22 | override fun flushAndSync() {
23 | out.flush()
24 | fd.sync()
25 | }
26 |
27 | @Throws(IOException::class)
28 | override fun close() {
29 | out.close()
30 | randomAccess.close()
31 | }
32 |
33 | @Throws(IOException::class)
34 | override fun seek(offset: Long) {
35 | randomAccess.seek(offset)
36 | }
37 |
38 | @Throws(IOException::class)
39 | override fun setLength(newLength: Long) {
40 | randomAccess.setLength(newLength)
41 | }
42 |
43 | companion object {
44 | @Throws(IOException::class)
45 | fun create(file: File): FileDownloadOutputStream {
46 | return FileDownloadRandomAccessFile(file)
47 | }
48 | }
49 | }
--------------------------------------------------------------------------------
/contentDownloader/src/main/java/com/p1mankar/contentdownloader/downloadModule/utils/Status.kt:
--------------------------------------------------------------------------------
1 | package com.p1mankar.filedownloader.downloadModule.utils
2 |
3 | enum class Status {
4 |
5 | QUEUED,
6 |
7 | RUNNING,
8 |
9 | PAUSED,
10 |
11 | COMPLETED,
12 |
13 | CANCELLED,
14 |
15 | FAILED,
16 |
17 | UNKNOWN
18 | }
--------------------------------------------------------------------------------
/contentDownloader/src/main/java/com/p1mankar/contentdownloader/downloadModule/utils/Utils.kt:
--------------------------------------------------------------------------------
1 | package com.p1mankar.filedownloader.downloadModule.utils
2 |
3 | import com.library.httpclient.HttpClient
4 | import com.p1mankar.filedownloader.downloadModule.http.DefaultHttpClient
5 | import com.p1mankar.filedownloader.downloadModule.internal.DownloadRequest
6 | import java.io.File
7 | import java.io.IOException
8 | import java.io.UnsupportedEncodingException
9 | import java.net.HttpURLConnection
10 | import java.security.MessageDigest
11 | import java.security.NoSuchAlgorithmException
12 | import kotlin.experimental.and
13 | private const val MAX_REDIRECTION = 10
14 |
15 | fun getPath(dirPath: String, fileName: String): String {
16 | return dirPath + File.separator + fileName
17 | }
18 |
19 | fun getTempPath(dirPath: String, fileName: String): String {
20 | return getPath(dirPath, fileName) + ".temp"
21 | }
22 |
23 | @Throws(IOException::class)
24 | fun renameFileName(oldPath: String, newPath: String) {
25 | val oldFile = File(oldPath)
26 | try {
27 | val newFile = File(newPath)
28 | if (newFile.exists()) {
29 | if (!newFile.delete()) {
30 | throw IOException("Deletion Failed")
31 | }
32 | }
33 | if (!oldFile.renameTo(newFile)) {
34 | throw IOException("Rename Failed")
35 | }
36 | } finally {
37 | if (oldFile.exists()) {
38 | oldFile.delete()
39 | }
40 | }
41 | }
42 |
43 | private fun isRedirection(code: Int): Boolean {
44 | return code == HttpURLConnection.HTTP_MOVED_PERM
45 | || code == HttpURLConnection.HTTP_MOVED_TEMP
46 | || code == HttpURLConnection.HTTP_SEE_OTHER
47 | || code == HttpURLConnection.HTTP_MULT_CHOICE
48 | // || code == Constants.HTTP_TEMPORARY_REDIRECT
49 | // || code == Constants.HTTP_PERMANENT_REDIRECT
50 | }
51 |
52 | @Throws(IOException::class, IllegalAccessException::class)
53 | fun getRedirectedConnectionIfAny(
54 | httpClient0: HttpClient,
55 | req: DownloadRequest
56 | ): HttpClient {
57 | var httpClient: HttpClient = httpClient0
58 | var redirectTimes = 0
59 | var code: Int = httpClient.getResponseCode()
60 | var location: String? = httpClient.getResponseHeader("Location")
61 | while (isRedirection(code)) {
62 | if (location == null) {
63 | throw IllegalAccessException("Location is null")
64 | }
65 | httpClient.close()
66 | req.url = (location)
67 | httpClient = DefaultHttpClient().clone()
68 | httpClient.connect(req)
69 | code = httpClient.getResponseCode()
70 | location = httpClient.getResponseHeader("Location")
71 | redirectTimes++
72 | if (redirectTimes >= MAX_REDIRECTION) {
73 | throw IllegalAccessException("Max redirection done")
74 | }
75 | }
76 | return httpClient
77 | }
78 |
79 | fun getUniqueId(url: String, dirPath: String, fileName: String): Int {
80 | val string = url + File.separator + dirPath + File.separator + fileName
81 | val hash: ByteArray = try {
82 | MessageDigest.getInstance("MD5").digest(string.toByteArray(charset("UTF-8")))
83 | } catch (e: NoSuchAlgorithmException) {
84 | throw RuntimeException("NoSuchAlgorithmException", e)
85 | } catch (e: UnsupportedEncodingException) {
86 | throw RuntimeException("UnsupportedEncodingException", e)
87 | }
88 | val hex = StringBuilder(hash.size * 2)
89 | for (b in hash) {
90 | if (b and 0xFF.toByte() < 0x10) hex.append("0")
91 | hex.append(Integer.toHexString((b and 0xFF.toByte()).toInt()))
92 | }
93 | return hex.toString().hashCode()
94 | }
95 |
96 | fun deleteFile(req: DownloadRequest) {
97 | val path = getTempPath(req.dirPath, req.fileName)
98 | val file = File(path)
99 | file.delete()
100 | }
--------------------------------------------------------------------------------
/contentDownloader/src/test/java/com/p1mankar/contentdownloader/ExampleUnitTest.kt:
--------------------------------------------------------------------------------
1 | package com.p1mankar.contentdownloader
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 | }
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. More details, visit
12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
13 | # org.gradle.parallel=true
14 | # AndroidX package structure to make it clearer which packages are bundled with the
15 | # Android operating system, and which are packaged with your app's APK
16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
17 | android.useAndroidX=true
18 | # Kotlin code style for this project: "official" or "obsolete":
19 | kotlin.code.style=official
20 | # Enables namespacing of each library's R class so that its R class includes only the
21 | # resources declared in the library itself and none from the library's dependencies,
22 | # thereby reducing the size of the R class for that library
23 | android.nonTransitiveRClass=true
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/pavanmankar/FileDownloader/9fd6b282803ef8814f4e2672c7d361260b296d68/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Thu Nov 16 12:02:01 IST 2023
2 | distributionBase=GRADLE_USER_HOME
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-bin.zip
4 | distributionPath=wrapper/dists
5 | zipStorePath=wrapper/dists
6 | zipStoreBase=GRADLE_USER_HOME
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | #
4 | # Copyright 2015 the original author or authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | ##
21 | ## Gradle start up script for UN*X
22 | ##
23 | ##############################################################################
24 |
25 | # Attempt to set APP_HOME
26 | # Resolve links: $0 may be a link
27 | PRG="$0"
28 | # Need this for relative symlinks.
29 | while [ -h "$PRG" ] ; do
30 | ls=`ls -ld "$PRG"`
31 | link=`expr "$ls" : '.*-> \(.*\)$'`
32 | if expr "$link" : '/.*' > /dev/null; then
33 | PRG="$link"
34 | else
35 | PRG=`dirname "$PRG"`"/$link"
36 | fi
37 | done
38 | SAVED="`pwd`"
39 | cd "`dirname \"$PRG\"`/" >/dev/null
40 | APP_HOME="`pwd -P`"
41 | cd "$SAVED" >/dev/null
42 |
43 | APP_NAME="Gradle"
44 | APP_BASE_NAME=`basename "$0"`
45 |
46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
48 |
49 | # Use the maximum available, or set MAX_FD != -1 to use that value.
50 | MAX_FD="maximum"
51 |
52 | warn () {
53 | echo "$*"
54 | }
55 |
56 | die () {
57 | echo
58 | echo "$*"
59 | echo
60 | exit 1
61 | }
62 |
63 | # OS specific support (must be 'true' or 'false').
64 | cygwin=false
65 | msys=false
66 | darwin=false
67 | nonstop=false
68 | case "`uname`" in
69 | CYGWIN* )
70 | cygwin=true
71 | ;;
72 | Darwin* )
73 | darwin=true
74 | ;;
75 | MINGW* )
76 | msys=true
77 | ;;
78 | NONSTOP* )
79 | nonstop=true
80 | ;;
81 | esac
82 |
83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
84 |
85 |
86 | # Determine the Java command to use to start the JVM.
87 | if [ -n "$JAVA_HOME" ] ; then
88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
89 | # IBM's JDK on AIX uses strange locations for the executables
90 | JAVACMD="$JAVA_HOME/jre/sh/java"
91 | else
92 | JAVACMD="$JAVA_HOME/bin/java"
93 | fi
94 | if [ ! -x "$JAVACMD" ] ; then
95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
96 |
97 | Please set the JAVA_HOME variable in your environment to match the
98 | location of your Java installation."
99 | fi
100 | else
101 | JAVACMD="java"
102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
103 |
104 | Please set the JAVA_HOME variable in your environment to match the
105 | location of your Java installation."
106 | fi
107 |
108 | # Increase the maximum file descriptors if we can.
109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
110 | MAX_FD_LIMIT=`ulimit -H -n`
111 | if [ $? -eq 0 ] ; then
112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
113 | MAX_FD="$MAX_FD_LIMIT"
114 | fi
115 | ulimit -n $MAX_FD
116 | if [ $? -ne 0 ] ; then
117 | warn "Could not set maximum file descriptor limit: $MAX_FD"
118 | fi
119 | else
120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
121 | fi
122 | fi
123 |
124 | # For Darwin, add options to specify how the application appears in the dock
125 | if $darwin; then
126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
127 | fi
128 |
129 | # For Cygwin or MSYS, switch paths to Windows format before running java
130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
133 |
134 | JAVACMD=`cygpath --unix "$JAVACMD"`
135 |
136 | # We build the pattern for arguments to be converted via cygpath
137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
138 | SEP=""
139 | for dir in $ROOTDIRSRAW ; do
140 | ROOTDIRS="$ROOTDIRS$SEP$dir"
141 | SEP="|"
142 | done
143 | OURCYGPATTERN="(^($ROOTDIRS))"
144 | # Add a user-defined pattern to the cygpath arguments
145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
147 | fi
148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
149 | i=0
150 | for arg in "$@" ; do
151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
153 |
154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
156 | else
157 | eval `echo args$i`="\"$arg\""
158 | fi
159 | i=`expr $i + 1`
160 | done
161 | case $i in
162 | 0) set -- ;;
163 | 1) set -- "$args0" ;;
164 | 2) set -- "$args0" "$args1" ;;
165 | 3) set -- "$args0" "$args1" "$args2" ;;
166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;;
167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
172 | esac
173 | fi
174 |
175 | # Escape application args
176 | save () {
177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
178 | echo " "
179 | }
180 | APP_ARGS=`save "$@"`
181 |
182 | # Collect all arguments for the java command, following the shell quoting and substitution rules
183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
184 |
185 | exec "$JAVACMD" "$@"
186 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%" == "" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%" == "" set DIRNAME=.
29 | set APP_BASE_NAME=%~n0
30 | set APP_HOME=%DIRNAME%
31 |
32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
34 |
35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
37 |
38 | @rem Find java.exe
39 | if defined JAVA_HOME goto findJavaFromJavaHome
40 |
41 | set JAVA_EXE=java.exe
42 | %JAVA_EXE% -version >NUL 2>&1
43 | if "%ERRORLEVEL%" == "0" goto execute
44 |
45 | echo.
46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
47 | echo.
48 | echo Please set the JAVA_HOME variable in your environment to match the
49 | echo location of your Java installation.
50 |
51 | goto fail
52 |
53 | :findJavaFromJavaHome
54 | set JAVA_HOME=%JAVA_HOME:"=%
55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
56 |
57 | if exist "%JAVA_EXE%" goto execute
58 |
59 | echo.
60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
61 | echo.
62 | echo Please set the JAVA_HOME variable in your environment to match the
63 | echo location of your Java installation.
64 |
65 | goto fail
66 |
67 | :execute
68 | @rem Setup the command line
69 |
70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
71 |
72 |
73 | @rem Execute Gradle
74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
75 |
76 | :end
77 | @rem End local scope for the variables with windows NT shell
78 | if "%ERRORLEVEL%"=="0" goto mainEnd
79 |
80 | :fail
81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
82 | rem the _cmd.exe /c_ return code!
83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
84 | exit /b 1
85 |
86 | :mainEnd
87 | if "%OS%"=="Windows_NT" endlocal
88 |
89 | :omega
90 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | pluginManagement {
2 | repositories {
3 | gradlePluginPortal()
4 | google()
5 | mavenCentral()
6 | }
7 | }
8 | dependencyResolutionManagement {
9 | repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
10 | repositories {
11 | google()
12 | mavenCentral()
13 | }
14 | }
15 | rootProject.name = "FileDownloader"
16 | include ':app'
17 | include ':contentDownloader'
18 |
--------------------------------------------------------------------------------