Skip to content

Commit b396370

Browse files
committed
[Android] deletes existing file when trying to create new file
1 parent cc62a52 commit b396370

File tree

1 file changed

+56
-18
lines changed

1 file changed

+56
-18
lines changed

android/src/main/kotlin/vn/hunghd/flutterdownloader/DownloadWorker.kt

+56-18
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,8 @@ class DownloadWorker(context: Context, params: WorkerParameters) :
148148
dbHelper = TaskDbHelper.getInstance(applicationContext)
149149
taskDao = TaskDao(dbHelper!!)
150150
val url: String =
151-
inputData.getString(ARG_URL) ?: throw IllegalArgumentException("Argument '$ARG_URL' should not be null")
151+
inputData.getString(ARG_URL)
152+
?: throw IllegalArgumentException("Argument '$ARG_URL' should not be null")
152153
val filename: String? =
153154
inputData.getString(ARG_FILE_NAME) // ?: throw IllegalArgumentException("Argument '$ARG_FILE_NAME' should not be null")
154155
val savedDir: String = inputData.getString(ARG_SAVED_DIR)
@@ -170,9 +171,9 @@ class DownloadWorker(context: Context, params: WorkerParameters) :
170171
val task = taskDao?.loadTask(id.toString())
171172
log(
172173
"DownloadWorker{url=$url,filename=$filename,savedDir=$savedDir,header=$headers,isResume=$isResume,status=" + (
173-
task?.status
174-
?: "GONE"
175-
)
174+
task?.status
175+
?: "GONE"
176+
)
176177
)
177178

178179
// Task has been deleted or cancelled
@@ -209,7 +210,14 @@ class DownloadWorker(context: Context, params: WorkerParameters) :
209210
taskDao = null
210211
Result.success()
211212
} catch (e: Exception) {
212-
updateNotification(applicationContext, filename ?: url, DownloadStatus.FAILED, -1, null, true)
213+
updateNotification(
214+
applicationContext,
215+
filename ?: url,
216+
DownloadStatus.FAILED,
217+
-1,
218+
null,
219+
true
220+
)
213221
taskDao?.updateTask(id.toString(), DownloadStatus.FAILED, lastProgress)
214222
e.printStackTrace()
215223
dbHelper = null
@@ -306,14 +314,16 @@ class DownloadWorker(context: Context, params: WorkerParameters) :
306314
log("Open connection to $url")
307315
httpConn.connectTimeout = actualTimeout
308316
httpConn.readTimeout = actualTimeout
309-
httpConn.instanceFollowRedirects = false // Make the logic below easier to detect redirections
317+
httpConn.instanceFollowRedirects =
318+
false // Make the logic below easier to detect redirections
310319
httpConn.setRequestProperty("User-Agent", "Mozilla/5.0...")
311320

312321
// setup request headers if it is set
313322
setupHeaders(httpConn, headers)
314323
// try to continue downloading a file from its partial downloaded data.
315324
if (isResume) {
316-
downloadedBytes = setupPartialDownloadedDataHeader(httpConn, actualFilename, savedDir)
325+
downloadedBytes =
326+
setupPartialDownloadedDataHeader(httpConn, actualFilename, savedDir)
317327
}
318328
responseCode = httpConn.responseCode
319329
when (responseCode) {
@@ -469,7 +479,14 @@ class DownloadWorker(context: Context, params: WorkerParameters) :
469479
}
470480
} catch (e: IOException) {
471481
taskDao!!.updateTask(id.toString(), DownloadStatus.FAILED, lastProgress)
472-
updateNotification(context, actualFilename ?: fileURL, DownloadStatus.FAILED, -1, null, true)
482+
updateNotification(
483+
context,
484+
actualFilename ?: fileURL,
485+
DownloadStatus.FAILED,
486+
-1,
487+
null,
488+
true
489+
)
473490
e.printStackTrace()
474491
} finally {
475492
if (outputStream != null) {
@@ -497,17 +514,33 @@ class DownloadWorker(context: Context, params: WorkerParameters) :
497514
private fun createFileInAppSpecificDir(filename: String, savedDir: String): File? {
498515
val newFile = File(savedDir, filename)
499516
try {
500-
val rs: Boolean = newFile.createNewFile()
501-
if (rs) {
502-
return newFile
503-
} else {
504-
logError("It looks like you are trying to save file in public storage but not setting 'saveInPublicStorage' to 'true'")
517+
if (newFile.exists()) {
518+
val deleted = newFile.delete()
519+
if (!deleted) {
520+
logError("Unable to delete existing file: ${newFile.absolutePath}")
521+
return null
522+
}
505523
}
524+
525+
val created: Boolean = newFile.createNewFile()
526+
if (!created) {
527+
logError(
528+
"""
529+
Unable to create new file: ${newFile.absolutePath}.
530+
Are are trying to save file in public storage
531+
but not setting 'saveInPublicStorage' to 'true'?
532+
""".trimIndent()
533+
)
534+
return null
535+
}
536+
537+
return newFile
538+
506539
} catch (e: IOException) {
507540
e.printStackTrace()
508541
logError("Create a file using java.io API failed ")
542+
return null
509543
}
510-
return null
511544
}
512545

513546
/**
@@ -602,15 +635,18 @@ class DownloadWorker(context: Context, params: WorkerParameters) :
602635
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
603636
// Create the NotificationChannel
604637
val res = applicationContext.resources
605-
val channelName: String = res.getString(R.string.flutter_downloader_notification_channel_name)
606-
val channelDescription: String = res.getString(R.string.flutter_downloader_notification_channel_description)
638+
val channelName: String =
639+
res.getString(R.string.flutter_downloader_notification_channel_name)
640+
val channelDescription: String =
641+
res.getString(R.string.flutter_downloader_notification_channel_description)
607642
val importance: Int = NotificationManager.IMPORTANCE_LOW
608643
val channel = NotificationChannel(CHANNEL_ID, channelName, importance)
609644
channel.description = channelDescription
610645
channel.setSound(null, null)
611646

612647
// Add the channel
613-
val notificationManager: NotificationManagerCompat = NotificationManagerCompat.from(context)
648+
val notificationManager: NotificationManagerCompat =
649+
NotificationManagerCompat.from(context)
614650
notificationManager.createNotificationChannel(channel)
615651
}
616652
}
@@ -769,7 +805,9 @@ class DownloadWorker(context: Context, params: WorkerParameters) :
769805

770806
private fun isImageOrVideoFile(contentType: String): Boolean {
771807
val newContentType = getContentTypeWithoutCharset(contentType)
772-
return newContentType != null && (newContentType.startsWith("image/") || newContentType.startsWith("video"))
808+
return newContentType != null && (newContentType.startsWith("image/") || newContentType.startsWith(
809+
"video"
810+
))
773811
}
774812

775813
private fun isExternalStoragePath(filePath: String?): Boolean {

0 commit comments

Comments
 (0)