Created
May 18, 2020 17:25
-
-
Save hiking93/f4c051ff4d517d0233fede4bedfd5872 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object YoutubeDlHelper { | |
enum class Selection(val value: Int) { | |
PREVIEW(0), | |
UNLOCKED(1) | |
} | |
private const val TAG = "youtube-dl" | |
fun download(url: String, selection: Selection, file: File, showDebugLogs: Boolean = true): Boolean { | |
Log.d(TAG, "Start downloading $url to ${file.path}") | |
val hasAudioTrack = checkAudioTrack(url, showDebugLogs) | |
val auth = Config.auth | |
val selectionValue = if (hasAudioTrack) "${selection.value}+bestaudio" else selection.value.toString() | |
val path = file.absolutePath.replace("%", "%%") | |
val command = "youtube-dl -f $selectionValue --add-header Authorization:\"$auth\" -o \"$path\" \"${url}\"" | |
try { | |
val process = Runtime.getRuntime().exec(command) | |
if (showDebugLogs) { | |
BufferedReader(InputStreamReader(process.inputStream)).useLines { lines -> | |
lines.forEach { Log.d(TAG, it) } | |
} | |
} | |
BufferedReader(InputStreamReader(process.errorStream)).useLines { lines -> | |
lines.forEach { Log.e(TAG, it) } | |
} | |
} catch (e: IOException) { | |
Log.d(TAG, "Download ${file.name} failed: ${e.javaClass.simpleName}, ${e.message}") | |
} | |
val isSuccessful = file.exists() | |
if (isSuccessful) { | |
Log.d(TAG, "Downloaded as ${file.name}.") | |
} | |
return isSuccessful | |
} | |
private fun checkAudioTrack(url: String, showDebugLogs: Boolean = false): Boolean { | |
var hasAudioTrack = false | |
val command = "youtube-dl -F \"$url\"" | |
try { | |
val process = Runtime.getRuntime().exec(command) | |
BufferedReader(InputStreamReader(process.inputStream)).useLines { lines -> | |
lines.forEach { | |
if (showDebugLogs) Log.d(TAG, it) | |
if (it.contains("DASH audio")) hasAudioTrack = true | |
} | |
} | |
BufferedReader(InputStreamReader(process.errorStream)).useLines { lines -> | |
lines.forEach { Log.e(TAG, it) } | |
} | |
} catch (e: IOException) { | |
e.printStackTrace() | |
} | |
return hasAudioTrack | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment