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:
@@ -1,65 +0,0 @@
|
||||
package bums.lunatic.launcher.utils
|
||||
|
||||
import android.util.Log
|
||||
import bums.lunatic.launcher.BuildConfig
|
||||
|
||||
object Blog {
|
||||
val DEFAULT_TAG = "Lunatic"
|
||||
enum class BLogType {
|
||||
D,I,E
|
||||
}
|
||||
fun w(tag : String = DEFAULT_TAG, log: String){
|
||||
LOG(BLogType.D,tag,log)
|
||||
}
|
||||
|
||||
fun LOGD(tag : String = DEFAULT_TAG, log: String){
|
||||
LOG(BLogType.D,tag,log)
|
||||
}
|
||||
|
||||
fun LOGI(tag : String = DEFAULT_TAG, log: String){
|
||||
LOG(BLogType.I,tag,log)
|
||||
}
|
||||
|
||||
fun LOGE(tag : String = DEFAULT_TAG, log: Throwable){
|
||||
LOG(BLogType.E,tag,log.toString())
|
||||
}
|
||||
|
||||
fun LOGE(tag : String = DEFAULT_TAG, log: Exception){
|
||||
LOG(BLogType.E,tag,log.toString())
|
||||
}
|
||||
|
||||
fun LOGE(tag : String = DEFAULT_TAG, log: String){
|
||||
LOG(BLogType.E,tag,log)
|
||||
}
|
||||
|
||||
fun LOGE(log: String){
|
||||
LOG(BLogType.E,DEFAULT_TAG,log)
|
||||
}
|
||||
|
||||
inline fun LOG(type : BLogType, tag : String, log : String) {
|
||||
val stackTrace = Thread.currentThread().stackTrace
|
||||
val blogIndex = stackTrace.indexOfLast { it.className.contains("Blog") }
|
||||
val callerInfo = if (blogIndex != -1 && blogIndex + 1 < stackTrace.size)
|
||||
stackTrace[blogIndex + 1]
|
||||
else null
|
||||
val fileName = callerInfo?.fileName ?: "Unknown"
|
||||
val className = callerInfo?.className ?: "Unknown"
|
||||
val methodName = callerInfo?.methodName ?: "Unknown"
|
||||
val lineNumber = callerInfo?.lineNumber ?: -1
|
||||
|
||||
if (BuildConfig.DEBUG || BuildConfig.BUILD_TYPE.contains("debug")) {
|
||||
when(type) {
|
||||
BLogType.D -> {
|
||||
Log.d(tag, ("${fileName}\n${className}\n${methodName} : ${lineNumber}\n" + log))
|
||||
}
|
||||
BLogType.I -> {
|
||||
Log.i(tag, ("${fileName}\n${className}\n${methodName} : ${lineNumber}\n" + log))
|
||||
}
|
||||
BLogType.E -> {
|
||||
Log.e(tag, ("${fileName}\n${className}\n${methodName} : ${lineNumber}\n" + log))
|
||||
}
|
||||
else -> {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,672 +0,0 @@
|
||||
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 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
|
||||
|
||||
|
||||
inner class TorrentBinder : Binder() {
|
||||
fun getService(): TorrentService = this@TorrentService
|
||||
}
|
||||
|
||||
@SuppressLint("ServiceCast")
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
|
||||
// if (!isKoreaRegion()) {
|
||||
// Blog.LOGE("해외 지역 접속 감지: 서비스를 종료합니다.")
|
||||
// stopForeground(true)
|
||||
// stopSelf()
|
||||
// return
|
||||
// }
|
||||
startForegroundService()
|
||||
initLibTorrent()
|
||||
|
||||
// 1. 초기 상태 체크 (배터리 및 네트워크)
|
||||
checkInitialStatus()
|
||||
|
||||
// 2. 리시버 및 콜백 등록
|
||||
registerBatteryReceiver()
|
||||
|
||||
|
||||
// 3. 초기 세션 상태 적용
|
||||
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
|
||||
|
||||
|
||||
}
|
||||
// TorrentService.kt에 추가
|
||||
fun prioritizeTorrent(infoHash: String) {
|
||||
try {
|
||||
session.find(Sha1Hash(infoHash))?.let { handle ->
|
||||
// 1. 큐(대기열) 포지션을 최상위(0)로 끌어올림
|
||||
handle.queuePositionTop()
|
||||
|
||||
// 💡 2. 수정된 부분: getter인 flags() 대신 SWIG의 unset_flags() 사용
|
||||
handle.swig().unset_flags(libtorrent.getAuto_managed())
|
||||
|
||||
// 3. 강제 재시작 (일시정지 상태였다면 즉시 시작)
|
||||
handle.resume()
|
||||
|
||||
// 4. 트래커 강제 재요청으로 피어 즉시 탐색 유도
|
||||
handle.forceReannounce()
|
||||
}
|
||||
|
||||
// UI 즉시 갱신
|
||||
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?) {
|
||||
// isCharging = when (intent?.action) {
|
||||
// Intent.ACTION_POWER_CONNECTED -> true
|
||||
// Intent.ACTION_POWER_DISCONNECTED -> false
|
||||
// else -> isCharging
|
||||
// }
|
||||
|
||||
val intent = registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
|
||||
|
||||
val level = intent?.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) ?: -1
|
||||
val scale = intent?.getIntExtra(BatteryManager.EXTRA_SCALE, -1) ?: -1
|
||||
val status = intent?.getIntExtra(BatteryManager.EXTRA_STATUS, -1) ?: -1
|
||||
val plugged = intent?.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1) ?: -1
|
||||
|
||||
batteryPct = (level / scale.toFloat() * 100).toInt()
|
||||
isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
|
||||
status == BatteryManager.BATTERY_STATUS_FULL || (batteryPct > 95)
|
||||
|
||||
var speedText = ""
|
||||
var detailsText = ""
|
||||
|
||||
// if (isCharging) {
|
||||
// speedText = when (plugged) {
|
||||
// BatteryManager.BATTERY_PLUGGED_AC -> "고속"
|
||||
// BatteryManager.BATTERY_PLUGGED_USB -> "저속"
|
||||
// BatteryManager.BATTERY_PLUGGED_WIRELESS -> "무선"
|
||||
// else -> ""
|
||||
// }
|
||||
//
|
||||
// // 1. 전압(Voltage) 가져오기: 기본 단위는 밀리볼트(mV)
|
||||
// val voltageMv = intent?.getIntExtra(BatteryManager.EXTRA_VOLTAGE, 0) ?: 0
|
||||
// val voltageV = voltageMv / 1000.0f
|
||||
//
|
||||
// // 2. 전류(Current) 가져오기: BatteryManager를 통해 실시간 값 조회
|
||||
// val batteryManager = getSystemService(BATTERY_SERVICE) as BatteryManager
|
||||
// // 안드로이드 표준 단위는 마이크로암페어(µA) 입니다.
|
||||
// val currentUa = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_NOW)
|
||||
//
|
||||
// // 음수(방전)로 나올 수 있으므로 절대값 처리 후 암페어(A)로 변환
|
||||
// val currentA = Math.abs(currentUa) / 1000000.0f
|
||||
//
|
||||
// // 3. 전력(Watt) 계산: W = V * A
|
||||
// val wattage = voltageV * currentA
|
||||
//
|
||||
// // 값이 정상적으로 읽혔을 때만 텍스트 생성 (가끔 0으로 떨어지는 기기 방어)
|
||||
// if (voltageV > 0f && currentA > 0f) {
|
||||
// detailsText = String.format("%.1fV %.1fA (%.1fW)", voltageV, currentA, wattage)
|
||||
// }
|
||||
// }
|
||||
// Blog.LOGE("detailsText >>> $detailsText")
|
||||
|
||||
updateSessionState()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
var lastUpdateTime = -1L
|
||||
/**
|
||||
* 핵심 제어 로직: 충전 중일 때만 세션을 열고, Wi-Fi 여부에 따라 슬롯 조절
|
||||
*/
|
||||
private fun updateSessionState() {
|
||||
// if (!isKoreaRegion()) {
|
||||
// Blog.LOGE("해외 지역 접속 감지: 서비스를 종료합니다.")
|
||||
// stopForeground(true)
|
||||
// stopSelf()
|
||||
// return
|
||||
// }
|
||||
|
||||
checkIpAndStop()
|
||||
|
||||
if (session.isPaused) session.resume()
|
||||
var curentTime = System.currentTimeMillis()
|
||||
if (curentTime - lastUpdateTime > 5000) {
|
||||
serviceScope.launch {
|
||||
lastUpdateTime = curentTime
|
||||
val vector = session.swig().get_torrents()
|
||||
// (핸들, 계산된 우선순위 점수)
|
||||
val torrentsWithMetadata = mutableListOf<kotlin.Pair<TorrentHandle, Int>>()
|
||||
val torrentsWithoutMetadata = mutableListOf<TorrentHandle>()
|
||||
|
||||
val LOW_SPEED_THRESHOLD = 10 * 1024 // 10 KB/s 미만을 '속도 저조'로 판단
|
||||
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()
|
||||
|
||||
// 💡 수정된 점수 계산 로직:
|
||||
// 큐 포지션이 0(사용자가 강제로 Top으로 올린 경우)이면 속도 페널티를 주지 않음
|
||||
val finalScore = if (basePriority == 0) {
|
||||
0 // 무조건 0순위 유지
|
||||
} else if (currentRate < LOW_SPEED_THRESHOLD) {
|
||||
basePriority + PENALTY_SCORE
|
||||
} else {
|
||||
basePriority
|
||||
}
|
||||
|
||||
torrentsWithMetadata.add(handle to finalScore)
|
||||
}
|
||||
}
|
||||
|
||||
// 1. 메타데이터 미수신: 무조건 유지
|
||||
|
||||
|
||||
// 2. 파일 다운로드: 계산된 점수(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
|
||||
|
||||
// 1. SIM 카드의 국가 코드 확인 (예: "kr")
|
||||
val simCountry = tm.simCountryIso.lowercase()
|
||||
|
||||
// 2. 네트워크(기지국) 기준 국가 코드 확인
|
||||
val networkCountry = tm.networkCountryIso.lowercase()
|
||||
|
||||
// SIM이나 네트워크 중 하나라도 'kr'이면 한국으로 판단
|
||||
return simCountry == "kr" || networkCountry == "kr"
|
||||
}
|
||||
|
||||
private fun checkIpAndStop() {
|
||||
serviceScope.launch(Dispatchers.IO) {
|
||||
try {
|
||||
// 외부 API를 통해 국가 코드 확인 (예: ip-api.com)
|
||||
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))
|
||||
}
|
||||
|
||||
// 트래커 추가 후 즉시 재요청(Force Reannounce)
|
||||
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 -> {
|
||||
(alert as MetadataReceivedAlert).handle().saveResumeData()
|
||||
}
|
||||
AlertType.SAVE_RESUME_DATA -> {
|
||||
val ra = alert as SaveResumeDataAlert
|
||||
saveResumeFile(ra.handle().infoHash().toString(), ra.params())
|
||||
}
|
||||
else -> {}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
session.start()
|
||||
|
||||
restoreExistingDownloads()
|
||||
updateTrackers()
|
||||
}
|
||||
|
||||
private var updateJob: Job? = null
|
||||
|
||||
// ✅ 추가할 함수: 다운로드 중일 때만 2초마다 가볍게 찔러줍니다.
|
||||
private fun startLightweightUpdater() {
|
||||
updateJob?.cancel()
|
||||
updateJob = serviceScope.launch {
|
||||
while (isActive) {
|
||||
updateSessionState()
|
||||
// 충전 중이고 세션이 돌아갈 때만 C++ 엔진에 상태 업데이트 요청
|
||||
var delayTime = 30000L
|
||||
if (isCharging) {
|
||||
session.postTorrentUpdates()
|
||||
|
||||
} else {
|
||||
delayTime = 60000L
|
||||
}
|
||||
delay(delayTime)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 리스너에 의해 호출되는 UI 및 데이터 갱신 함수
|
||||
*/
|
||||
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 stateText = when {
|
||||
isFinished -> "완료"
|
||||
!status.hasMetadata() -> "메타데이터 수신 중..."
|
||||
!isCharging -> "충전 대기 중"
|
||||
isDownloading -> "다운로드 중"
|
||||
isPaused -> "일시정지"
|
||||
else -> "대기 중"
|
||||
}
|
||||
|
||||
tasks.add(TorrentTask(
|
||||
infoHash = status.infoHash().toString(),
|
||||
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
|
||||
}
|
||||
|
||||
// 1. 메타데이터 수신 중인 파일 수
|
||||
val metadataCount = tasks.count { it.stateText == "메타데이터 수신 중..." }
|
||||
|
||||
// 2. 실제 다운로드 중인 파일들 (충전/와이파이 조건으로 활성화된 것들)
|
||||
val downloadingTasks = tasks.filter { it.isPaused == false }.filter { it.stateText == "다운로드 중" }
|
||||
val downloadingCount = downloadingTasks.size
|
||||
|
||||
// 3. 다운로드 중인 파일들의 평균 진행률
|
||||
val averageProgress = if (downloadingTasks.isNotEmpty()) {
|
||||
downloadingTasks.map { it.progress }.average().toInt()
|
||||
} else {
|
||||
0
|
||||
}
|
||||
|
||||
// 4. 전체 다운로드/업로드 속도 (Session에서 직접 가져옴)
|
||||
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 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)
|
||||
File(resumeDir, "${status.infoHash()}.resume").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)
|
||||
} catch (e: Exception) { e.printStackTrace() }
|
||||
}
|
||||
|
||||
private fun restoreExistingDownloads() {
|
||||
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)
|
||||
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)
|
||||
|
||||
// 수동 제어를 위해 auto_managed 해제
|
||||
var flags = swigParams.flags
|
||||
flags = flags.and_(libtorrent.getAuto_managed().inv())
|
||||
swigParams.flags = flags
|
||||
|
||||
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()
|
||||
// 💡 UI 즉시 갱신: 수동 조작 시 답답하지 않게 바로 상태를 업데이트합니다.
|
||||
refreshTorrentStats()
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
}
|
||||
}
|
||||
|
||||
fun pauseTorrent(infoHash: String) {
|
||||
try {
|
||||
session.find(Sha1Hash(infoHash))?.let {
|
||||
it.pause()
|
||||
// 대기열 맨 뒤로 보내기 (선택 사항)
|
||||
// it.queuePositionBottom()
|
||||
}
|
||||
refreshTorrentStats()
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
}
|
||||
}
|
||||
|
||||
fun removeTorrent(infoHash: String, deleteFile: Boolean) {
|
||||
try {
|
||||
val handle = session.find(Sha1Hash(infoHash))
|
||||
if (handle != null) {
|
||||
// 1. 실제 파일 삭제 (요청 시)
|
||||
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()
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 엔진에서 세션 제거
|
||||
session.remove(handle)
|
||||
|
||||
// 3. 리쥼(이어받기) 데이터 파일 삭제
|
||||
val resumeFile = File(resumeDir, "$infoHash.resume")
|
||||
if (resumeFile.exists()) {
|
||||
resumeFile.delete()
|
||||
}
|
||||
|
||||
// 💡 삭제 후 목록에서 즉시 사라지도록 UI 갱신
|
||||
refreshTorrentStats()
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user