LibreTube/app/src/main/java/com/github/libretube/DownloadService.kt

275 lines
12 KiB
Kotlin
Raw Normal View History

2022-03-03 12:08:36 +05:30
package com.github.libretube
2022-05-21 13:32:04 +05:30
import android.app.DownloadManager
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
2022-03-03 12:08:36 +05:30
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.graphics.Color
import android.net.Uri
import android.os.Build
import android.os.Environment
2022-05-21 13:32:04 +05:30
import android.os.Environment.DIRECTORY_DOWNLOADS
2022-03-03 12:08:36 +05:30
import android.os.IBinder
import android.util.Log
import androidx.core.app.NotificationCompat
2022-03-05 00:22:30 +05:30
import androidx.core.app.NotificationManagerCompat
2022-03-03 12:08:36 +05:30
import com.arthenica.ffmpegkit.FFmpegKit
import java.io.File
2022-03-04 23:30:50 +05:30
2022-03-04 21:27:10 +05:30
var IS_DOWNLOAD_RUNNING = false
2022-05-21 13:32:04 +05:30
2022-05-20 03:52:10 +05:30
class DownloadService : Service() {
2022-03-03 12:08:36 +05:30
val TAG = "DownloadService"
2022-05-20 03:52:10 +05:30
private var downloadId: Long = -1
2022-03-03 12:08:36 +05:30
private lateinit var videoId: String
private lateinit var videoUrl: String
private lateinit var audioUrl: String
2022-03-04 21:27:10 +05:30
private lateinit var extension: String
2022-03-03 12:08:36 +05:30
private var duration: Int = 0
2022-05-21 13:32:04 +05:30
2022-05-20 03:52:10 +05:30
// private lateinit var command: String
2022-03-03 12:08:36 +05:30
private lateinit var audioDir: File
private lateinit var videoDir: File
2022-03-04 22:59:57 +05:30
lateinit var service: NotificationManager
lateinit var notification: NotificationCompat.Builder
2022-03-04 21:27:10 +05:30
override fun onCreate() {
super.onCreate()
IS_DOWNLOAD_RUNNING = true
}
2022-03-03 12:08:36 +05:30
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
videoId = intent?.getStringExtra("videoId")!!
videoUrl = intent.getStringExtra("videoUrl")!!
audioUrl = intent.getStringExtra("audioUrl")!!
2022-03-04 21:27:10 +05:30
extension = intent.getStringExtra("extension")!!
2022-05-20 03:52:10 +05:30
// command = intent.getStringExtra("command")!!
duration = intent.getIntExtra("duration", 1)
2022-03-04 22:59:57 +05:30
service = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
2022-05-20 03:52:10 +05:30
val channelId =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val chan = NotificationChannel(
"service",
"DownloadService", NotificationManager.IMPORTANCE_NONE
)
chan.lightColor = Color.BLUE
chan.lockscreenVisibility = Notification.VISIBILITY_PRIVATE
service.createNotificationChannel(chan)
"service"
} else {
// If earlier version channel ID is not used
// https://developer.android.com/reference/android/support/v4/app/NotificationCompat.Builder.html#NotificationCompat.Builder(android.content.Context)
""
}
2022-03-04 23:30:50 +05:30
var pendingIntent: PendingIntent? = null
pendingIntent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_MUTABLE)
} else {
PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT)
}
2022-05-20 03:52:10 +05:30
// Creating a notification and setting its various attributes
2022-03-04 22:59:57 +05:30
notification =
NotificationCompat.Builder(this@DownloadService, channelId)
.setSmallIcon(R.drawable.ic_download)
.setContentTitle("LibreTube")
.setContentText("Downloading")
.setPriority(NotificationCompat.PRIORITY_LOW)
.setOngoing(true)
.setOnlyAlertOnce(true)
.setProgress(100, 0, true)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
2022-05-20 03:52:10 +05:30
startForeground(1, notification.build())
2022-03-03 12:08:36 +05:30
downloadManager()
return super.onStartCommand(intent, flags, startId)
}
2022-05-21 13:32:04 +05:30
2022-03-03 12:08:36 +05:30
override fun onBind(intent: Intent?): IBinder? {
TODO("Not yet implemented")
}
private fun downloadManager() {
val path = applicationContext.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
val folder_main = ".tmp"
val f = File(path, folder_main)
if (!f.exists()) {
f.mkdirs()
Log.e(TAG, "Directory make")
} else {
2022-03-04 21:27:10 +05:30
f.deleteRecursively()
f.mkdirs()
2022-03-03 12:08:36 +05:30
Log.e(TAG, "Directory already have")
}
audioDir = File(f, "$videoId-audio")
videoDir = File(f, "$videoId-video")
try {
Log.e(TAG, "Directory make")
2022-05-21 13:32:04 +05:30
registerReceiver(
onDownloadComplete,
IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)
)
2022-03-03 12:08:36 +05:30
val request: DownloadManager.Request =
DownloadManager.Request(Uri.parse(videoUrl))
.setTitle("Video") // Title of the Download Notification
.setDescription("Downloading") // Description of the Download Notification
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE) // Visibility of the download Notification
.setDestinationUri(Uri.fromFile(videoDir))
.setAllowedOverMetered(true) // Set if download is allowed on Mobile network
.setAllowedOverRoaming(true) //
val downloadManager: DownloadManager =
applicationContext.getSystemService(DOWNLOAD_SERVICE) as DownloadManager
downloadId = downloadManager.enqueue(request)
2022-05-21 13:32:04 +05:30
if (audioUrl == "") {
downloadId = 0L
}
2022-03-03 12:08:36 +05:30
} catch (e: IllegalArgumentException) {
Log.e(TAG, "download error $e")
2022-05-20 03:52:10 +05:30
try {
2022-03-04 21:27:10 +05:30
downloadId = 0L
val request: DownloadManager.Request =
DownloadManager.Request(Uri.parse(audioUrl))
.setTitle("Audio") // Title of the Download Notification
.setDescription("Downloading") // Description of the Download Notification
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE) // Visibility of the download Notification
.setDestinationUri(Uri.fromFile(audioDir))
.setAllowedOverMetered(true) // Set if download is allowed on Mobile network
.setAllowedOverRoaming(true) //
val downloadManager: DownloadManager =
applicationContext.getSystemService(DOWNLOAD_SERVICE) as DownloadManager
downloadManager.enqueue(request)
2022-05-20 03:52:10 +05:30
} catch (e: Exception) {
2022-03-04 21:27:10 +05:30
Log.e(TAG, "audio download error $e")
2022-05-20 03:52:10 +05:30
stopService(Intent(this, DownloadService::class.java))
}
2022-03-03 12:08:36 +05:30
}
}
private val onDownloadComplete: BroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
2022-05-20 03:52:10 +05:30
// Fetching the download id received with the broadcast
2022-03-03 12:08:36 +05:30
val id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1)
2022-05-20 03:52:10 +05:30
// Checking if the received broadcast is for our enqueued download by matching download id
2022-03-03 12:08:36 +05:30
if (downloadId == id) {
2022-05-20 03:52:10 +05:30
downloadId = 0L
try {
val request: DownloadManager.Request =
DownloadManager.Request(Uri.parse(audioUrl))
.setTitle("Audio") // Title of the Download Notification
.setDescription("Downloading") // Description of the Download Notification
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE) // Visibility of the download Notification
.setDestinationUri(Uri.fromFile(audioDir))
.setAllowedOverMetered(true) // Set if download is allowed on Mobile network
.setAllowedOverRoaming(true) //
val downloadManager: DownloadManager =
applicationContext.getSystemService(DOWNLOAD_SERVICE) as DownloadManager
downloadManager.enqueue(request)
2022-05-21 13:32:04 +05:30
} catch (e: Exception) {
}
2022-05-20 03:52:10 +05:30
} else if (downloadId == 0L) {
2022-05-21 13:32:04 +05:30
val libreTube = File(
Environment.getExternalStoragePublicDirectory(DIRECTORY_DOWNLOADS), "LibreTube"
)
2022-03-04 21:27:10 +05:30
if (!libreTube.exists()) {
libreTube.mkdirs()
Log.e(TAG, "libreTube Directory make")
} else {
Log.e(TAG, "libreTube Directory already have")
}
var command: String = when {
2022-05-20 03:52:10 +05:30
videoUrl == "" -> {
"-y -i $audioDir -c copy $libreTube/$videoId-audio$extension"
2022-03-04 21:27:10 +05:30
}
2022-05-20 03:52:10 +05:30
audioUrl == "" -> {
"-y -i $videoDir -c copy $libreTube/$videoId-video$extension"
2022-03-04 21:27:10 +05:30
}
else -> {
2022-05-20 03:52:10 +05:30
"-y -i $videoDir -i $audioDir -c copy $libreTube/${videoId}$extension"
2022-03-04 21:27:10 +05:30
}
}
2022-03-04 22:59:57 +05:30
notification.setContentTitle("Muxing")
2022-05-20 03:52:10 +05:30
FFmpegKit.executeAsync(
command,
2022-03-03 12:08:36 +05:30
{ session ->
val state = session.state
val returnCode = session.returnCode
// CALLED WHEN SESSION IS EXECUTED
Log.d(
TAG,
String.format(
"FFmpeg process exited with state %s and rc %s.%s",
state,
returnCode,
session.failStackTrace
)
)
2022-05-21 13:32:04 +05:30
val path =
applicationContext.getExternalFilesDir(DIRECTORY_DOWNLOADS)
2022-03-03 12:08:36 +05:30
val folder_main = ".tmp"
val f = File(path, folder_main)
f.deleteRecursively()
2022-05-20 03:52:10 +05:30
if (returnCode.toString() != "0") {
2022-03-05 00:22:30 +05:30
var builder = NotificationCompat.Builder(this@DownloadService, "failed")
.setSmallIcon(R.drawable.ic_download)
.setContentTitle(resources.getString(R.string.downloadfailed))
.setContentText("failure")
.setPriority(NotificationCompat.PRIORITY_HIGH)
createNotificationChannel()
with(NotificationManagerCompat.from(this@DownloadService)) {
// notificationId is a unique int for each notification that you must define
notify(69, builder.build())
}
}
2022-03-04 22:59:57 +05:30
stopForeground(true)
2022-05-20 03:52:10 +05:30
stopService(Intent(this@DownloadService, DownloadService::class.java))
2022-03-03 12:08:36 +05:30
}, {
2022-05-20 03:52:10 +05:30
// CALLED WHEN SESSION PRINTS LOGS
Log.e(TAG, it.message.toString())
}
) {
2022-03-03 12:08:36 +05:30
// CALLED WHEN SESSION GENERATES STATISTICS
2022-05-20 03:52:10 +05:30
Log.e(TAG + "stat", it.time.toString())
2022-03-04 21:27:10 +05:30
/*val progress = it.time/(10*duration!!)
2022-03-03 12:08:36 +05:30
if (progress<1){
notification
.setProgress(progressMax, progress.toInt(), false)
service.notify(1,notification.build())
2022-03-04 21:27:10 +05:30
}*/
2022-03-03 12:08:36 +05:30
}
}
}
}
2022-03-05 00:22:30 +05:30
private fun createNotificationChannel() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val name = "failed"
val descriptionText = "Download Failed"
val importance = NotificationManager.IMPORTANCE_DEFAULT
val channel = NotificationChannel("failed", name, importance).apply {
description = descriptionText
}
// Register the channel with the system
val notificationManager: NotificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
}
2022-05-21 13:32:04 +05:30
2022-03-03 12:08:36 +05:30
override fun onDestroy() {
2022-03-04 21:27:10 +05:30
try {
unregisterReceiver(onDownloadComplete)
2022-05-21 13:32:04 +05:30
} catch (e: Exception) {
}
2022-03-04 21:27:10 +05:30
IS_DOWNLOAD_RUNNING = false
2022-05-20 03:52:10 +05:30
Log.d(TAG, "dl finished!")
2022-03-03 12:08:36 +05:30
super.onDestroy()
}
}