build: Task 20 완료 - Blog 코어 이동 및 :feature:feature-torrent 모듈 분리
- core/core-common: buildConfig 활성화 및 Blog.kt를 :app에서 :core:core-common으로 이동 - feature/feature-torrent 모듈 신규 생성 (namespace: bums.lunatic.launcher.feature.torrent): * TorrentManager.kt(TorrentService, TorrentTask)를 :app에서 :feature:feature-torrent로 이동 * jlibtorrent-2.0.12.7.jar 및 ABI별 jlibtorrent-android-*.jar 5종을 feature/feature-torrent/libs/로 격리 및 api 노출 - settings.gradle.kts & app/build.gradle.kts: :feature:feature-torrent 모듈 등록 및 :app 의존성 연결 - TODO.md: 6-2(:feature:torrent 분리) 진행 내역 반영 - 검증: ./gradlew :app:compileDebugKotlin 빌드 성공 확인 (18s, 73 actionable tasks)
This commit is contained in:
@@ -0,0 +1,29 @@
|
||||
plugins {
|
||||
id("com.android.library")
|
||||
id("kotlin-android")
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "bums.lunatic.launcher.feature.torrent"
|
||||
compileSdk = 35
|
||||
|
||||
defaultConfig {
|
||||
minSdk = 26
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_1_8
|
||||
targetCompatibility = JavaVersion.VERSION_1_8
|
||||
}
|
||||
|
||||
kotlinOptions {
|
||||
jvmTarget = "1.8"
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation(project(":core:core-common"))
|
||||
api(fileTree(mapOf("dir" to "libs", "include" to listOf("jlibtorrent-*.jar"))))
|
||||
implementation("androidx.core:core-ktx:1.15.0")
|
||||
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3")
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,2 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest />
|
||||
+710
@@ -0,0 +1,710 @@
|
||||
package bums.lunatic.launcher.workers
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.app.*
|
||||
import android.content.*
|
||||
import android.net.*
|
||||
import android.os.*
|
||||
import androidx.annotation.RequiresApi
|
||||
import androidx.core.app.NotificationCompat
|
||||
import bums.lunatic.launcher.utils.Blog
|
||||
import com.frostwire.jlibtorrent.*
|
||||
import com.frostwire.jlibtorrent.alerts.*
|
||||
import com.frostwire.jlibtorrent.swig.error_code
|
||||
import com.frostwire.jlibtorrent.swig.libtorrent
|
||||
import com.frostwire.jlibtorrent.swig.settings_pack
|
||||
import com.frostwire.jlibtorrent.swig.torrent_status
|
||||
import kotlinx.coroutines.*
|
||||
import java.io.File
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
import android.telephony.TelephonyManager
|
||||
|
||||
data class TorrentTask(
|
||||
val infoHash: String,
|
||||
val name: String,
|
||||
val progress: Float,
|
||||
val isPaused: Boolean,
|
||||
val isQueued: Boolean,
|
||||
val stateText: String
|
||||
)
|
||||
|
||||
class TorrentService : Service() {
|
||||
|
||||
private lateinit var session: SessionManager
|
||||
private val binder = TorrentBinder()
|
||||
private val serviceScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
|
||||
|
||||
// 경로 설정
|
||||
private val tempDir by lazy { File(getExternalFilesDir(null), "temp_torrents").apply { mkdirs() } }
|
||||
private val resumeDir by lazy { File(getExternalFilesDir(null), "resume_data").apply { mkdirs() } }
|
||||
|
||||
// 알림 및 상태 관리
|
||||
private lateinit var notificationManager: NotificationManager
|
||||
private lateinit var notificationBuilder: NotificationCompat.Builder
|
||||
private val NOTIFICATION_ID = 101
|
||||
private var lastProgress = -1
|
||||
|
||||
// 제어 플래그
|
||||
private var isWifiConnected = false
|
||||
private var isCharging = false
|
||||
|
||||
// 미리보기용 핵심 조각 인덱스 저장 맵 (infoHash -> Set<PieceIndex>)
|
||||
private val previewPiecesMap = ConcurrentHashMap<String, Set<Int>>()
|
||||
|
||||
companion object {
|
||||
const val PREVIEW_FRAME_COUNT = 30
|
||||
}
|
||||
|
||||
inner class TorrentBinder : Binder() {
|
||||
fun getService(): TorrentService = this@TorrentService
|
||||
}
|
||||
|
||||
@SuppressLint("ServiceCast")
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
|
||||
startForegroundService()
|
||||
initLibTorrent()
|
||||
|
||||
checkInitialStatus()
|
||||
registerBatteryReceiver()
|
||||
updateSessionState()
|
||||
startLightweightUpdater()
|
||||
}
|
||||
|
||||
private fun checkInitialStatus() {
|
||||
val ifilter = IntentFilter(Intent.ACTION_BATTERY_CHANGED)
|
||||
val batteryStatus = registerReceiver(null, ifilter)
|
||||
val status = batteryStatus?.getIntExtra(BatteryManager.EXTRA_STATUS, -1) ?: -1
|
||||
isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL
|
||||
}
|
||||
|
||||
fun prioritizeTorrent(infoHash: String) {
|
||||
try {
|
||||
session.find(Sha1Hash(infoHash))?.let { handle ->
|
||||
handle.queuePositionTop()
|
||||
handle.swig().unset_flags(libtorrent.getAuto_managed())
|
||||
handle.resume()
|
||||
handle.forceReannounce()
|
||||
}
|
||||
|
||||
refreshTorrentStats()
|
||||
updateSessionState()
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
}
|
||||
}
|
||||
|
||||
private fun registerBatteryReceiver() {
|
||||
val filter = IntentFilter().apply {
|
||||
addAction(Intent.ACTION_POWER_CONNECTED)
|
||||
addAction(Intent.ACTION_POWER_DISCONNECTED)
|
||||
addAction(Intent.ACTION_BATTERY_CHANGED)
|
||||
}
|
||||
registerReceiver(batteryReceiver, filter)
|
||||
}
|
||||
|
||||
var batteryPct = 50
|
||||
private val batteryReceiver = object : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context?, intent: Intent?) {
|
||||
val batteryIntent = registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
|
||||
|
||||
val level = batteryIntent?.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) ?: -1
|
||||
val scale = batteryIntent?.getIntExtra(BatteryManager.EXTRA_SCALE, -1) ?: -1
|
||||
val status = batteryIntent?.getIntExtra(BatteryManager.EXTRA_STATUS, -1) ?: -1
|
||||
|
||||
batteryPct = (level / scale.toFloat() * 100).toInt()
|
||||
isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
|
||||
status == BatteryManager.BATTERY_STATUS_FULL || (batteryPct > 95)
|
||||
|
||||
updateSessionState()
|
||||
}
|
||||
}
|
||||
|
||||
var lastUpdateTime = -1L
|
||||
|
||||
private fun updateSessionState() {
|
||||
checkIpAndStop()
|
||||
|
||||
if (session.isPaused) session.resume()
|
||||
val currentTime = System.currentTimeMillis()
|
||||
if (currentTime - lastUpdateTime > 5000) {
|
||||
serviceScope.launch {
|
||||
lastUpdateTime = currentTime
|
||||
val vector = session.swig().get_torrents()
|
||||
val torrentsWithMetadata = mutableListOf<kotlin.Pair<TorrentHandle, Int>>()
|
||||
val torrentsWithoutMetadata = mutableListOf<TorrentHandle>()
|
||||
|
||||
val LOW_SPEED_THRESHOLD = 10 * 1024
|
||||
val PENALTY_SCORE = 1000
|
||||
|
||||
for (i in 0 until vector.size.toInt()) {
|
||||
val handle = TorrentHandle(vector.get(i))
|
||||
if (!handle.isValid) continue
|
||||
|
||||
val status = handle.status()
|
||||
if (!status.hasMetadata()) {
|
||||
torrentsWithoutMetadata.add(handle)
|
||||
} else if (!status.isFinished) {
|
||||
val currentRate = status.downloadPayloadRate()
|
||||
val basePriority = status.queuePosition()
|
||||
|
||||
val finalScore = if (basePriority == 0) {
|
||||
0
|
||||
} else if (currentRate < LOW_SPEED_THRESHOLD) {
|
||||
basePriority + PENALTY_SCORE
|
||||
} else {
|
||||
basePriority
|
||||
}
|
||||
|
||||
torrentsWithMetadata.add(handle to finalScore)
|
||||
}
|
||||
}
|
||||
|
||||
if (isCharging && batteryPct > 75) {
|
||||
torrentsWithoutMetadata.forEach { it.swig().resume() }
|
||||
val maxSlots = if (isWifiConnected) 8 else 3
|
||||
val sortedByPriority = torrentsWithMetadata.sortedBy { it.second }
|
||||
|
||||
sortedByPriority.forEachIndexed { index, pair ->
|
||||
val handle = pair.first
|
||||
if (index < maxSlots) {
|
||||
handle.swig().resume()
|
||||
} else {
|
||||
handle.pause()
|
||||
}
|
||||
}
|
||||
} else {
|
||||
torrentsWithoutMetadata.forEach { it.swig().pause() }
|
||||
torrentsWithMetadata.forEach { it.first.pause() }
|
||||
}
|
||||
|
||||
refreshTorrentStats()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun isKoreaRegion(): Boolean {
|
||||
val tm = getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
|
||||
val simCountry = tm.simCountryIso.lowercase()
|
||||
val networkCountry = tm.networkCountryIso.lowercase()
|
||||
return simCountry == "kr" || networkCountry == "kr"
|
||||
}
|
||||
|
||||
private fun checkIpAndStop() {
|
||||
serviceScope.launch(Dispatchers.IO) {
|
||||
try {
|
||||
val response = java.net.URL("http://ip-api.com/json/").readText()
|
||||
if (!response.contains("\"countryCode\":\"KR\"")) {
|
||||
withContext(Dispatchers.Main) {
|
||||
Blog.LOGE("IP 위치가 대한민국이 아닙니다. 다운로드를 중지합니다.")
|
||||
session.pause()
|
||||
stopSelf()
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
// 네트워크 오류 시 보수적으로 처리
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private val TRACKER_URL = "https://raw.githubusercontent.com/ngosang/trackerslist/master/trackers_best.txt"
|
||||
|
||||
private fun updateTrackers() {
|
||||
serviceScope.launch(Dispatchers.IO) {
|
||||
try {
|
||||
val trackers = java.net.URL(TRACKER_URL).readText()
|
||||
.split("\n")
|
||||
.filter { it.isNotBlank() }
|
||||
|
||||
val vector = session.swig().get_torrents()
|
||||
for (i in 0 until vector.size.toInt()) {
|
||||
val handle = TorrentHandle(vector.get(i))
|
||||
if (!handle.isValid) continue
|
||||
|
||||
trackers.forEach { trackerUrl ->
|
||||
handle.addTracker(AnnounceEntry(trackerUrl))
|
||||
}
|
||||
handle.forceReannounce()
|
||||
}
|
||||
println("TorrentService: ${trackers.size}개의 트래커 주입 완료")
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun initLibTorrent() {
|
||||
session = SessionManager()
|
||||
val sp = SettingsPack()
|
||||
|
||||
sp.setInteger(settings_pack.int_types.in_enc_policy.swigValue(), settings_pack.enc_policy.pe_enabled.swigValue())
|
||||
sp.setInteger(settings_pack.int_types.out_enc_policy.swigValue(), settings_pack.enc_policy.pe_enabled.swigValue())
|
||||
sp.setBoolean(settings_pack.bool_types.enable_dht.swigValue(), true)
|
||||
sp.setBoolean(settings_pack.bool_types.enable_lsd.swigValue(), true)
|
||||
sp.setBoolean(settings_pack.bool_types.enable_upnp.swigValue(), true)
|
||||
sp.setBoolean(settings_pack.bool_types.enable_natpmp.swigValue(), true)
|
||||
sp.setInteger(settings_pack.int_types.connections_limit.swigValue(), 1000)
|
||||
|
||||
sp.setBoolean(settings_pack.bool_types.enable_incoming_utp.swigValue(), true)
|
||||
sp.setBoolean(settings_pack.bool_types.enable_outgoing_utp.swigValue(), true)
|
||||
|
||||
sp.setInteger(settings_pack.int_types.dht_announce_interval.swigValue(), 300)
|
||||
|
||||
sp.connectionsLimit(1000)
|
||||
sp.activeDownloads(10)
|
||||
sp.activeLimit(10)
|
||||
|
||||
session.applySettings(sp)
|
||||
|
||||
session.addListener(object : AlertListener {
|
||||
override fun types(): IntArray? = intArrayOf(
|
||||
AlertType.TORRENT_FINISHED.swig(),
|
||||
AlertType.METADATA_RECEIVED.swig(),
|
||||
AlertType.STATE_UPDATE.swig(),
|
||||
AlertType.SAVE_RESUME_DATA.swig()
|
||||
)
|
||||
|
||||
@RequiresApi(Build.VERSION_CODES.Q)
|
||||
override fun alert(alert: Alert<*>) {
|
||||
when (alert.type()) {
|
||||
AlertType.STATE_UPDATE -> refreshTorrentStats()
|
||||
AlertType.TORRENT_FINISHED -> {
|
||||
moveToPrivateStorage((alert as TorrentFinishedAlert).handle())
|
||||
refreshTorrentStats()
|
||||
}
|
||||
AlertType.METADATA_RECEIVED -> {
|
||||
val handle = (alert as MetadataReceivedAlert).handle()
|
||||
handle.swig().set_flags(libtorrent.getSequential_download())
|
||||
prioritizePreviewPieces(handle)
|
||||
handle.saveResumeData()
|
||||
}
|
||||
AlertType.SAVE_RESUME_DATA -> {
|
||||
val ra = alert as SaveResumeDataAlert
|
||||
saveResumeFile(ra.handle().infoHash().toString(), ra.params())
|
||||
}
|
||||
else -> {}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
session.start()
|
||||
|
||||
restoreExistingDownloads()
|
||||
updateTrackers()
|
||||
}
|
||||
|
||||
/**
|
||||
* 미리보기(30개 프레임)를 위해 영상의 앞/뒤 헤더 및 30등분 샘플 조각을 최우선 다운로드로 설정
|
||||
*/
|
||||
private fun prioritizePreviewPieces(handle: TorrentHandle) {
|
||||
try {
|
||||
val ti = handle.torrentFile() ?: return
|
||||
if (!ti.isValid) return
|
||||
|
||||
val files = ti.files()
|
||||
val videoExts = setOf("mp4", "mkv", "avi", "mov", "wmv", "flv", "webm", "ts")
|
||||
val pieceLength = ti.pieceLength().toLong()
|
||||
if (pieceLength <= 0L) return
|
||||
|
||||
val allTargetPieces = mutableSetOf<Int>()
|
||||
|
||||
for (i in 0 until files.numFiles()) {
|
||||
val fileName = files.fileName(i).lowercase()
|
||||
val ext = fileName.substringAfterLast('.', "")
|
||||
if (!videoExts.contains(ext)) continue
|
||||
|
||||
val fileOffset = files.fileOffset(i)
|
||||
val fileSize = files.fileSize(i)
|
||||
if (fileSize <= 0L) continue
|
||||
|
||||
val startPiece = (fileOffset / pieceLength).toInt()
|
||||
val endPiece = ((fileOffset + fileSize - 1) / pieceLength).toInt()
|
||||
val totalFilePieces = endPiece - startPiece + 1
|
||||
|
||||
val fileTargetPieces = mutableSetOf<Int>()
|
||||
|
||||
// 1. 파일 앞부분 헤더 (최대 5조각)
|
||||
for (p in startPiece until minOf(startPiece + 5, endPiece + 1)) {
|
||||
fileTargetPieces.add(p)
|
||||
}
|
||||
// 2. 파일 끝부분 인덱스/moov 아톰 (최대 3조각)
|
||||
for (p in maxOf(startPiece, endPiece - 2)..endPiece) {
|
||||
fileTargetPieces.add(p)
|
||||
}
|
||||
// 3. 미리보기 그리드(30등분) 지점별 샘플 조각
|
||||
val step = maxOf(1, totalFilePieces / PREVIEW_FRAME_COUNT)
|
||||
for (k in 1 until PREVIEW_FRAME_COUNT) {
|
||||
val samplePiece = startPiece + (step * k)
|
||||
if (samplePiece <= endPiece) {
|
||||
fileTargetPieces.add(samplePiece)
|
||||
if (samplePiece + 1 <= endPiece) fileTargetPieces.add(samplePiece + 1)
|
||||
}
|
||||
}
|
||||
|
||||
fileTargetPieces.forEachIndexed { idx, pieceIndex ->
|
||||
handle.piecePriority(pieceIndex, Priority.SEVEN)
|
||||
handle.setPieceDeadline(pieceIndex, 1000 + (idx * 150))
|
||||
}
|
||||
|
||||
allTargetPieces.addAll(fileTargetPieces)
|
||||
}
|
||||
|
||||
if (allTargetPieces.isNotEmpty()) {
|
||||
val hash = handle.infoHash().toString()
|
||||
previewPiecesMap[hash] = allTargetPieces
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
}
|
||||
}
|
||||
|
||||
private fun getPreviewStatusTag(handle: TorrentHandle, hashStr: String, status: TorrentStatus): String {
|
||||
if (!status.hasMetadata() || status.isFinished) return ""
|
||||
|
||||
var targetPieces = previewPiecesMap[hashStr]
|
||||
if (targetPieces == null) {
|
||||
prioritizePreviewPieces(handle)
|
||||
targetPieces = previewPiecesMap[hashStr] ?: return ""
|
||||
}
|
||||
|
||||
if (targetPieces.isEmpty()) return ""
|
||||
|
||||
val downloadedCount = targetPieces.count { pieceIdx -> handle.havePiece(pieceIdx) }
|
||||
val totalCount = targetPieces.size
|
||||
|
||||
return if (downloadedCount >= totalCount) {
|
||||
" [미리보기 가능]"
|
||||
} else {
|
||||
" [미리보기 $downloadedCount/$totalCount]"
|
||||
}
|
||||
}
|
||||
|
||||
private var updateJob: Job? = null
|
||||
|
||||
private fun startLightweightUpdater() {
|
||||
updateJob?.cancel()
|
||||
updateJob = serviceScope.launch {
|
||||
while (isActive) {
|
||||
updateSessionState()
|
||||
var delayTime = 30000L
|
||||
if (isCharging) {
|
||||
session.postTorrentUpdates()
|
||||
} else {
|
||||
delayTime = 60000L
|
||||
}
|
||||
delay(delayTime)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun refreshTorrentStats() {
|
||||
serviceScope.launch {
|
||||
val vector = session.swig().get_torrents()
|
||||
val tasks = mutableListOf<TorrentTask>()
|
||||
|
||||
for (i in 0 until vector.size.toInt()) {
|
||||
val handle = TorrentHandle(vector.get(i))
|
||||
if (!handle.isValid) continue
|
||||
|
||||
val status = handle.status()
|
||||
val state = status.state()
|
||||
|
||||
val hashStr = status.infoHash().toString()
|
||||
var rawName = status.name()
|
||||
|
||||
if (status.hasMetadata()) {
|
||||
val torrentInfo = handle.torrentFile()
|
||||
if (torrentInfo != null && torrentInfo.isValid) {
|
||||
val realName = torrentInfo.name()
|
||||
if (!realName.isNullOrEmpty()) {
|
||||
rawName = realName
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val displayName = if (rawName.isNullOrEmpty() || rawName == hashStr) {
|
||||
if (status.hasMetadata()) {
|
||||
"파일 정보 분석 중..."
|
||||
} else {
|
||||
"메타데이터 수신 중... (${hashStr.take(6)})"
|
||||
}
|
||||
} else {
|
||||
rawName
|
||||
}
|
||||
|
||||
val isPaused = status.flags().and_(libtorrent.getPaused()).nonZero()
|
||||
val isFinished = status.isFinished
|
||||
val isDownloading = (state.swig() == torrent_status.state_t.downloading.swigValue())
|
||||
val previewTag = getPreviewStatusTag(handle, hashStr, status)
|
||||
|
||||
val stateText = when {
|
||||
isFinished -> "완료"
|
||||
!status.hasMetadata() -> "메타데이터 수신 중..."
|
||||
!isCharging -> "충전 대기 중$previewTag"
|
||||
isDownloading -> "다운로드 중$previewTag"
|
||||
isPaused -> "일시정지$previewTag"
|
||||
else -> "대기 중$previewTag"
|
||||
}
|
||||
|
||||
tasks.add(
|
||||
TorrentTask(
|
||||
infoHash = hashStr,
|
||||
name = displayName,
|
||||
progress = status.progress() * 100f,
|
||||
isPaused = isPaused,
|
||||
isQueued = !isPaused && !isFinished && !isDownloading,
|
||||
stateText = stateText
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
_torrentTasks.value = tasks
|
||||
updateNotification(tasks)
|
||||
}
|
||||
}
|
||||
|
||||
private fun updateNotification(tasks: List<TorrentTask>) {
|
||||
if (tasks.isEmpty()) {
|
||||
notificationManager.cancel(NOTIFICATION_ID)
|
||||
return
|
||||
}
|
||||
|
||||
val metadataCount = tasks.count { it.stateText == "메타데이터 수신 중..." }
|
||||
val downloadingTasks = tasks.filter { !it.isPaused && it.stateText.startsWith("다운로드 중") }
|
||||
val downloadingCount = downloadingTasks.size
|
||||
|
||||
val averageProgress = if (downloadingTasks.isNotEmpty()) {
|
||||
downloadingTasks.map { it.progress }.average().toInt()
|
||||
} else {
|
||||
0
|
||||
}
|
||||
|
||||
val stats = session.stats()
|
||||
val downloadSpeed = formatSpeed(stats.downloadRate())
|
||||
val uploadSpeed = formatSpeed(stats.uploadRate())
|
||||
|
||||
val title = if (downloadingCount > 0) {
|
||||
"총 ${tasks.size} | 다운 ${downloadingCount} | 메타 ${metadataCount} | 대기 ${tasks.size - (downloadingCount + metadataCount)}"
|
||||
} else {
|
||||
"대기 중"
|
||||
}
|
||||
val content = StringBuilder().apply {
|
||||
append("평균 다운 진행율 $averageProgress% | ")
|
||||
append("↓ $downloadSpeed ↑ $uploadSpeed")
|
||||
}.toString()
|
||||
|
||||
notificationBuilder
|
||||
.setContentTitle(title)
|
||||
.setContentText(content)
|
||||
.setProgress(100, averageProgress, downloadingCount == 0 && metadataCount > 0)
|
||||
|
||||
notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build())
|
||||
}
|
||||
|
||||
private fun formatSpeed(bytesPerSecond: Long): String {
|
||||
val kb = bytesPerSecond / 1024.0
|
||||
return if (kb >= 1024) {
|
||||
String.format("%.1f MB/s", kb / 1024.0)
|
||||
} else {
|
||||
String.format("%.1f KB/s", kb)
|
||||
}
|
||||
}
|
||||
|
||||
@RequiresApi(Build.VERSION_CODES.Q)
|
||||
private fun moveToPrivateStorage(handle: TorrentHandle) {
|
||||
try {
|
||||
val status = handle.status()
|
||||
val hashStr = status.infoHash().toString()
|
||||
val torrentName = if (status.hasMetadata()) handle.torrentFile()?.name() ?: status.name() else status.name()
|
||||
val sourcePath = File(tempDir, torrentName)
|
||||
val destPath = File(File(getExternalFilesDir(null), "completed_torrents").apply { mkdirs() }, torrentName)
|
||||
|
||||
if (sourcePath.exists()) {
|
||||
if (!sourcePath.renameTo(destPath)) {
|
||||
sourcePath.copyRecursively(destPath, overwrite = true)
|
||||
sourcePath.deleteRecursively()
|
||||
}
|
||||
session.remove(handle)
|
||||
previewPiecesMap.remove(hashStr)
|
||||
File(resumeDir, "$hashStr.resume").delete()
|
||||
File(resumeDir, "$hashStr.magnet").delete()
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
}
|
||||
}
|
||||
|
||||
private fun saveResumeFile(hash: String, params: AddTorrentParams) {
|
||||
try {
|
||||
val data = Vectors.byte_vector2bytes(libtorrent.write_resume_data_buf_ex(params.swig()))
|
||||
File(resumeDir, "$hash.resume").writeBytes(data)
|
||||
File(resumeDir, "$hash.magnet").delete()
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
}
|
||||
}
|
||||
|
||||
private fun restoreExistingDownloads() {
|
||||
val restoredHashes = mutableSetOf<String>()
|
||||
|
||||
// 1. 메타데이터가 확보된 기존 .resume 파일 먼저 복원
|
||||
resumeDir.listFiles()?.filter { it.extension == "resume" }?.forEach { file ->
|
||||
try {
|
||||
val data = file.readBytes()
|
||||
val swigParams = libtorrent.read_resume_data_ex(Vectors.bytes2byte_vector(data), error_code())
|
||||
swigParams.setSave_path(tempDir.absolutePath)
|
||||
|
||||
var flags = swigParams.flags
|
||||
flags = flags.and_(libtorrent.getAuto_managed().inv())
|
||||
flags = flags.or_(libtorrent.getSequential_download())
|
||||
swigParams.flags = flags
|
||||
|
||||
session.swig().async_add_torrent(swigParams)
|
||||
restoredHashes.add(file.nameWithoutExtension)
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
}
|
||||
}
|
||||
|
||||
// 2. .resume이 없는 .magnet 파일 복원 (메타데이터 수신 중 프로세스 종료된 항목)
|
||||
resumeDir.listFiles()?.filter { it.extension == "magnet" }?.forEach { file ->
|
||||
try {
|
||||
val hash = file.nameWithoutExtension
|
||||
if (restoredHashes.contains(hash)) {
|
||||
file.delete()
|
||||
return@forEach
|
||||
}
|
||||
|
||||
val magnetUri = file.readText(Charsets.UTF_8).trim()
|
||||
if (magnetUri.isNotEmpty()) {
|
||||
val error = error_code()
|
||||
val swigParams = libtorrent.parse_magnet_uri(magnetUri, error)
|
||||
if (error.value() == 0) {
|
||||
swigParams.setSave_path(tempDir.absolutePath)
|
||||
|
||||
var flags = swigParams.flags
|
||||
flags = flags.and_(libtorrent.getAuto_managed().inv())
|
||||
flags = flags.or_(libtorrent.getSequential_download())
|
||||
swigParams.flags = flags
|
||||
|
||||
session.swig().async_add_torrent(swigParams)
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
intent?.getStringExtra("EXTRA_MAGNET_URI")?.let { addMagnet(it) }
|
||||
intent?.getBooleanExtra("WIFI_STATE", false)?.let {
|
||||
isWifiConnected = it
|
||||
}
|
||||
return START_STICKY
|
||||
}
|
||||
|
||||
fun addMagnet(magnetUri: String) {
|
||||
try {
|
||||
val error = error_code()
|
||||
val swigParams = libtorrent.parse_magnet_uri(magnetUri, error)
|
||||
if (error.value() == 0) {
|
||||
swigParams.setSave_path(tempDir.absolutePath)
|
||||
|
||||
var flags = swigParams.flags
|
||||
flags = flags.and_(libtorrent.getAuto_managed().inv())
|
||||
flags = flags.or_(libtorrent.getSequential_download())
|
||||
swigParams.flags = flags
|
||||
|
||||
val infoHash = if (swigParams.info_hashes.has_v1()) {
|
||||
Sha1Hash(swigParams.info_hashes.v1).toString()
|
||||
} else {
|
||||
""
|
||||
}
|
||||
|
||||
if (infoHash.isNotEmpty()) {
|
||||
File(resumeDir, "$infoHash.magnet").writeText(magnetUri, Charsets.UTF_8)
|
||||
}
|
||||
|
||||
session.swig().async_add_torrent(swigParams)
|
||||
updateSessionState()
|
||||
}
|
||||
updateTrackers()
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
}
|
||||
}
|
||||
|
||||
private fun startForegroundService() {
|
||||
val channelId = "torrent_channel"
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
notificationManager.createNotificationChannel(
|
||||
NotificationChannel(channelId, "Torrent Service", NotificationManager.IMPORTANCE_LOW)
|
||||
)
|
||||
}
|
||||
notificationBuilder = NotificationCompat.Builder(this, channelId)
|
||||
.setSmallIcon(android.R.drawable.stat_sys_download)
|
||||
.setOnlyAlertOnce(true)
|
||||
.setOngoing(true)
|
||||
startForeground(NOTIFICATION_ID, notificationBuilder.build())
|
||||
}
|
||||
|
||||
private val _torrentTasks = kotlinx.coroutines.flow.MutableStateFlow<List<TorrentTask>>(emptyList())
|
||||
val torrentTasks: kotlinx.coroutines.flow.StateFlow<List<TorrentTask>> = _torrentTasks
|
||||
|
||||
override fun onBind(intent: Intent): IBinder = binder
|
||||
|
||||
override fun onDestroy() {
|
||||
super.onDestroy()
|
||||
try {
|
||||
unregisterReceiver(batteryReceiver)
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
}
|
||||
serviceScope.cancel()
|
||||
}
|
||||
|
||||
fun resumeTorrent(infoHash: String) {
|
||||
try {
|
||||
session.find(Sha1Hash(infoHash))?.resume()
|
||||
refreshTorrentStats()
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
}
|
||||
}
|
||||
|
||||
fun pauseTorrent(infoHash: String) {
|
||||
try {
|
||||
session.find(Sha1Hash(infoHash))?.pause()
|
||||
refreshTorrentStats()
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
}
|
||||
}
|
||||
|
||||
fun removeTorrent(infoHash: String, deleteFile: Boolean) {
|
||||
try {
|
||||
val handle = session.find(Sha1Hash(infoHash))
|
||||
if (handle != null) {
|
||||
if (deleteFile) {
|
||||
val status = handle.status()
|
||||
val torrentName = if (status.hasMetadata()) handle.torrentFile()?.name() ?: status.name() else status.name()
|
||||
val targetFile = File(tempDir, torrentName)
|
||||
if (targetFile.exists()) {
|
||||
targetFile.deleteRecursively()
|
||||
}
|
||||
}
|
||||
session.remove(handle)
|
||||
}
|
||||
|
||||
previewPiecesMap.remove(infoHash)
|
||||
File(resumeDir, "$infoHash.resume").delete()
|
||||
File(resumeDir, "$infoHash.magnet").delete()
|
||||
|
||||
refreshTorrentStats()
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user