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:
2026-11-16 13:16:50 +09:00
parent f23cc1aa05
commit 1ff26530e3
14 changed files with 314 additions and 245 deletions
+1 -1
View File
@@ -183,6 +183,6 @@ lunar_launcher/
#### 단계별 모듈화 실행 순서 #### 단계별 모듈화 실행 순서
- [x] **6-1. `:core:common`, `:core:network`, `:core:database` 분리** (`:core:core-common`, `:core:core-network` 생성 및 `NetworkClient`·`MlKitTranslationHelper` 이동 완료; `:core:database`는 후속 진행) - [x] **6-1. `:core:common`, `:core:network`, `:core:database` 분리** (`:core:core-common`, `:core:core-network` 생성 및 `NetworkClient`·`MlKitTranslationHelper` 이동 완료; `:core:database`는 후속 진행)
- [ ] **6-2. 독립 기능 우선 분리 (`:feature:torrent`, `:feature:wallpaper`)**: `jlibtorrent` JAR들과 `MyWallpaperService`+`Renderer.cpp`는 타 화면과 결합도가 낮아 가장 먼저 독립 모듈로 분리하기 적합함. - [x] **6-2. 독립 기능 우선 분리 (`:feature:torrent`, `:feature:wallpaper`)** (`:feature:feature-torrent` 분리 및 `jlibtorrent` JAR 격리 완료; `:feature:wallpaper`는 후속 진행)
- [ ] **6-3. 뷰어/리더 분리 (`:feature:player`, `:feature:reader`)**: `PlayerActivity`/`NativePlayer`(+ `PlayerEngine.cpp`)와 `DocumentViewerActivity`/`ImageViewerActivity`, `TokiFragment`/`WebReaderActivity`를 분리. - [ ] **6-3. 뷰어/리더 분리 (`:feature:player`, `:feature:reader`)**: `PlayerActivity`/`NativePlayer`(+ `PlayerEngine.cpp`)와 `DocumentViewerActivity`/`ImageViewerActivity`, `TokiFragment`/`WebReaderActivity`를 분리.
- [ ] **6-4. 피드/수집기 분리 (`:feature:feeds`)**: `RssHome`, `NeoRssActivity`, `TaskAggregator`, `*Getter`군을 분리하고 `:app`은 런처 홈과 서비스 진입점만 유지. - [ ] **6-4. 피드/수집기 분리 (`:feature:feeds`)**: `RssHome`, `NeoRssActivity`, `TaskAggregator`, `*Getter`군을 분리하고 `:app`은 런처 홈과 서비스 진입점만 유지.
+1
View File
@@ -137,6 +137,7 @@ dependencies {
))) )))
implementation(project(":core:core-common")) implementation(project(":core:core-common"))
implementation(project(":core:core-network")) implementation(project(":core:core-network"))
implementation(project(":feature:feature-torrent"))
implementation(project(":gdrive")) implementation(project(":gdrive"))
implementation("com.google.android.gms:play-services-wearable:19.0.0") implementation("com.google.android.gms:play-services-wearable:19.0.0")
val kotlinVersion: String? by extra val kotlinVersion: String? by extra
@@ -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 -> {}
}
}
}
}
+4
View File
@@ -11,6 +11,10 @@ android {
minSdk = 26 minSdk = 26
} }
buildFeatures {
buildConfig = true
}
compileOptions { compileOptions {
sourceCompatibility = JavaVersion.VERSION_1_8 sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8 targetCompatibility = JavaVersion.VERSION_1_8
@@ -0,0 +1,59 @@
package bums.lunatic.launcher.utils
import android.util.Log
import bums.lunatic.launcher.core.common.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")
}
}
}
}
+29
View File
@@ -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")
}
@@ -0,0 +1,2 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest />
@@ -16,7 +16,9 @@ import com.frostwire.jlibtorrent.swig.settings_pack
import com.frostwire.jlibtorrent.swig.torrent_status import com.frostwire.jlibtorrent.swig.torrent_status
import kotlinx.coroutines.* import kotlinx.coroutines.*
import java.io.File import java.io.File
import java.util.concurrent.ConcurrentHashMap
import android.telephony.TelephonyManager import android.telephony.TelephonyManager
data class TorrentTask( data class TorrentTask(
val infoHash: String, val infoHash: String,
val name: String, val name: String,
@@ -46,6 +48,12 @@ class TorrentService : Service() {
private var isWifiConnected = false private var isWifiConnected = false
private var isCharging = 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() { inner class TorrentBinder : Binder() {
fun getService(): TorrentService = this@TorrentService fun getService(): TorrentService = this@TorrentService
@@ -55,63 +63,38 @@ class TorrentService : Service() {
override fun onCreate() { override fun onCreate() {
super.onCreate() super.onCreate()
notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
// if (!isKoreaRegion()) {
// Blog.LOGE("해외 지역 접속 감지: 서비스를 종료합니다.")
// stopForeground(true)
// stopSelf()
// return
// }
startForegroundService() startForegroundService()
initLibTorrent() initLibTorrent()
// 1. 초기 상태 체크 (배터리 및 네트워크)
checkInitialStatus() checkInitialStatus()
// 2. 리시버 및 콜백 등록
registerBatteryReceiver() registerBatteryReceiver()
// 3. 초기 세션 상태 적용
updateSessionState() updateSessionState()
startLightweightUpdater() startLightweightUpdater()
} }
private fun checkInitialStatus() { private fun checkInitialStatus() {
// 배터리 상태
val ifilter = IntentFilter(Intent.ACTION_BATTERY_CHANGED) val ifilter = IntentFilter(Intent.ACTION_BATTERY_CHANGED)
val batteryStatus = registerReceiver(null, ifilter) val batteryStatus = registerReceiver(null, ifilter)
val status = batteryStatus?.getIntExtra(BatteryManager.EXTRA_STATUS, -1) ?: -1 val status = batteryStatus?.getIntExtra(BatteryManager.EXTRA_STATUS, -1) ?: -1
isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL
} }
// TorrentService.kt에 추가
fun prioritizeTorrent(infoHash: String) { fun prioritizeTorrent(infoHash: String) {
try { try {
session.find(Sha1Hash(infoHash))?.let { handle -> session.find(Sha1Hash(infoHash))?.let { handle ->
// 1. 큐(대기열) 포지션을 최상위(0)로 끌어올림
handle.queuePositionTop() handle.queuePositionTop()
// 💡 2. 수정된 부분: getter인 flags() 대신 SWIG의 unset_flags() 사용
handle.swig().unset_flags(libtorrent.getAuto_managed()) handle.swig().unset_flags(libtorrent.getAuto_managed())
// 3. 강제 재시작 (일시정지 상태였다면 즉시 시작)
handle.resume() handle.resume()
// 4. 트래커 강제 재요청으로 피어 즉시 탐색 유도
handle.forceReannounce() handle.forceReannounce()
} }
// UI 즉시 갱신
refreshTorrentStats() refreshTorrentStats()
// 전체 세션 상태 재평가 (다른 것들을 멈추고 얘를 켤 수 있도록)
updateSessionState() updateSessionState()
} catch (e: Exception) { } catch (e: Exception) {
e.printStackTrace() e.printStackTrace()
} }
} }
private fun registerBatteryReceiver() { private fun registerBatteryReceiver() {
val filter = IntentFilter().apply { val filter = IntentFilter().apply {
addAction(Intent.ACTION_POWER_CONNECTED) addAction(Intent.ACTION_POWER_CONNECTED)
@@ -120,92 +103,40 @@ class TorrentService : Service() {
} }
registerReceiver(batteryReceiver, filter) registerReceiver(batteryReceiver, filter)
} }
var batteryPct = 50
var batteryPct = 50
private val batteryReceiver = object : BroadcastReceiver() { private val batteryReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) { override fun onReceive(context: Context?, intent: Intent?) {
// isCharging = when (intent?.action) { val batteryIntent = registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
// Intent.ACTION_POWER_CONNECTED -> true
// Intent.ACTION_POWER_DISCONNECTED -> false
// else -> isCharging
// }
val intent = 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 level = intent?.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) ?: -1 val status = batteryIntent?.getIntExtra(BatteryManager.EXTRA_STATUS, -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() batteryPct = (level / scale.toFloat() * 100).toInt()
isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
status == BatteryManager.BATTERY_STATUS_FULL || (batteryPct > 95) 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() updateSessionState()
} }
} }
var lastUpdateTime = -1L var lastUpdateTime = -1L
/**
* 핵심 제어 로직: 충전 중일 때만 세션을 열고, Wi-Fi 여부에 따라 슬롯 조절
*/
private fun updateSessionState() {
// if (!isKoreaRegion()) {
// Blog.LOGE("해외 지역 접속 감지: 서비스를 종료합니다.")
// stopForeground(true)
// stopSelf()
// return
// }
private fun updateSessionState() {
checkIpAndStop() checkIpAndStop()
if (session.isPaused) session.resume() if (session.isPaused) session.resume()
var curentTime = System.currentTimeMillis() val currentTime = System.currentTimeMillis()
if (curentTime - lastUpdateTime > 5000) { if (currentTime - lastUpdateTime > 5000) {
serviceScope.launch { serviceScope.launch {
lastUpdateTime = curentTime lastUpdateTime = currentTime
val vector = session.swig().get_torrents() val vector = session.swig().get_torrents()
// (핸들, 계산된 우선순위 점수)
val torrentsWithMetadata = mutableListOf<kotlin.Pair<TorrentHandle, Int>>() val torrentsWithMetadata = mutableListOf<kotlin.Pair<TorrentHandle, Int>>()
val torrentsWithoutMetadata = mutableListOf<TorrentHandle>() val torrentsWithoutMetadata = mutableListOf<TorrentHandle>()
val LOW_SPEED_THRESHOLD = 10 * 1024 // 10 KB/s 미만을 '속도 저조'로 판단 val LOW_SPEED_THRESHOLD = 10 * 1024
val PENALTY_SCORE = 1000 // 속도가 낮을 경우 부여할 페널티 (대기열 순서보다 큰 값) val PENALTY_SCORE = 1000
for (i in 0 until vector.size.toInt()) { for (i in 0 until vector.size.toInt()) {
val handle = TorrentHandle(vector.get(i)) val handle = TorrentHandle(vector.get(i))
@@ -218,10 +149,8 @@ var batteryPct = 50
val currentRate = status.downloadPayloadRate() val currentRate = status.downloadPayloadRate()
val basePriority = status.queuePosition() val basePriority = status.queuePosition()
// 💡 수정된 점수 계산 로직:
// 큐 포지션이 0(사용자가 강제로 Top으로 올린 경우)이면 속도 페널티를 주지 않음
val finalScore = if (basePriority == 0) { val finalScore = if (basePriority == 0) {
0 // 무조건 0순위 유지 0
} else if (currentRate < LOW_SPEED_THRESHOLD) { } else if (currentRate < LOW_SPEED_THRESHOLD) {
basePriority + PENALTY_SCORE basePriority + PENALTY_SCORE
} else { } else {
@@ -232,10 +161,6 @@ var batteryPct = 50
} }
} }
// 1. 메타데이터 미수신: 무조건 유지
// 2. 파일 다운로드: 계산된 점수(finalScore)가 낮은 순으로 정렬
if (isCharging && batteryPct > 75) { if (isCharging && batteryPct > 75) {
torrentsWithoutMetadata.forEach { it.swig().resume() } torrentsWithoutMetadata.forEach { it.swig().resume() }
val maxSlots = if (isWifiConnected) 8 else 3 val maxSlots = if (isWifiConnected) 8 else 3
@@ -251,7 +176,6 @@ var batteryPct = 50
} }
} else { } else {
torrentsWithoutMetadata.forEach { it.swig().pause() } torrentsWithoutMetadata.forEach { it.swig().pause() }
// 배터리 모드
torrentsWithMetadata.forEach { it.first.pause() } torrentsWithMetadata.forEach { it.first.pause() }
} }
@@ -262,41 +186,30 @@ var batteryPct = 50
private fun isKoreaRegion(): Boolean { private fun isKoreaRegion(): Boolean {
val tm = getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager val tm = getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
// 1. SIM 카드의 국가 코드 확인 (예: "kr")
val simCountry = tm.simCountryIso.lowercase() val simCountry = tm.simCountryIso.lowercase()
// 2. 네트워크(기지국) 기준 국가 코드 확인
val networkCountry = tm.networkCountryIso.lowercase() val networkCountry = tm.networkCountryIso.lowercase()
// SIM이나 네트워크 중 하나라도 'kr'이면 한국으로 판단
return simCountry == "kr" || networkCountry == "kr" return simCountry == "kr" || networkCountry == "kr"
} }
private fun checkIpAndStop() { private fun checkIpAndStop() {
serviceScope.launch(Dispatchers.IO) { serviceScope.launch(Dispatchers.IO) {
try { try {
// 외부 API를 통해 국가 코드 확인 (예: ip-api.com)
val response = java.net.URL("http://ip-api.com/json/").readText() val response = java.net.URL("http://ip-api.com/json/").readText()
if (!response.contains("\"countryCode\":\"KR\"")) { if (!response.contains("\"countryCode\":\"KR\"")) {
withContext(Dispatchers.Main) { withContext(Dispatchers.Main) {
Blog.LOGE("IP 위치가 대한민국이 아닙니다. 다운로드를 중지합니다.") Blog.LOGE("IP 위치가 대한민국이 아닙니다. 다운로드를 중지합니다.")
// 모든 토렌트 일시정지 또는 서비스 종료
session.pause() session.pause()
stopSelf() stopSelf()
} }
} }
} catch (e: Exception) { } catch (e: Exception) {
// 네트워크 오류 시 보수적으로 처리 (선택 사항) // 네트워크 오류 시 보수적으로 처리
} }
} }
} }
private val TRACKER_URL = "https://raw.githubusercontent.com/ngosang/trackerslist/master/trackers_best.txt" private val TRACKER_URL = "https://raw.githubusercontent.com/ngosang/trackerslist/master/trackers_best.txt"
/**
* 전 세계 최신 트래커 리스트를 가져와 현재 모든 토렌트에 주입합니다.
*/
private fun updateTrackers() { private fun updateTrackers() {
serviceScope.launch(Dispatchers.IO) { serviceScope.launch(Dispatchers.IO) {
try { try {
@@ -309,12 +222,9 @@ var batteryPct = 50
val handle = TorrentHandle(vector.get(i)) val handle = TorrentHandle(vector.get(i))
if (!handle.isValid) continue if (!handle.isValid) continue
// 각 트래커를 토렌트에 추가
trackers.forEach { trackerUrl -> trackers.forEach { trackerUrl ->
handle.addTracker(AnnounceEntry(trackerUrl)) handle.addTracker(AnnounceEntry(trackerUrl))
} }
// 트래커 추가 후 즉시 재요청(Force Reannounce)
handle.forceReannounce() handle.forceReannounce()
} }
println("TorrentService: ${trackers.size}개의 트래커 주입 완료") println("TorrentService: ${trackers.size}개의 트래커 주입 완료")
@@ -328,12 +238,11 @@ var batteryPct = 50
session = SessionManager() session = SessionManager()
val sp = SettingsPack() 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.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.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_dht.swigValue(), true)
sp.setBoolean(settings_pack.bool_types.enable_lsd.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_upnp.swigValue(), true)
sp.setBoolean(settings_pack.bool_types.enable_natpmp.swigValue(), true) sp.setBoolean(settings_pack.bool_types.enable_natpmp.swigValue(), true)
sp.setInteger(settings_pack.int_types.connections_limit.swigValue(), 1000) sp.setInteger(settings_pack.int_types.connections_limit.swigValue(), 1000)
@@ -365,7 +274,10 @@ var batteryPct = 50
refreshTorrentStats() refreshTorrentStats()
} }
AlertType.METADATA_RECEIVED -> { AlertType.METADATA_RECEIVED -> {
(alert as MetadataReceivedAlert).handle().saveResumeData() val handle = (alert as MetadataReceivedAlert).handle()
handle.swig().set_flags(libtorrent.getSequential_download())
prioritizePreviewPieces(handle)
handle.saveResumeData()
} }
AlertType.SAVE_RESUME_DATA -> { AlertType.SAVE_RESUME_DATA -> {
val ra = alert as SaveResumeDataAlert val ra = alert as SaveResumeDataAlert
@@ -382,19 +294,102 @@ var batteryPct = 50
updateTrackers() 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 var updateJob: Job? = null
// ✅ 추가할 함수: 다운로드 중일 때만 2초마다 가볍게 찔러줍니다.
private fun startLightweightUpdater() { private fun startLightweightUpdater() {
updateJob?.cancel() updateJob?.cancel()
updateJob = serviceScope.launch { updateJob = serviceScope.launch {
while (isActive) { while (isActive) {
updateSessionState() updateSessionState()
// 충전 중이고 세션이 돌아갈 때만 C++ 엔진에 상태 업데이트 요청
var delayTime = 30000L var delayTime = 30000L
if (isCharging) { if (isCharging) {
session.postTorrentUpdates() session.postTorrentUpdates()
} else { } else {
delayTime = 60000L delayTime = 60000L
} }
@@ -403,9 +398,6 @@ var batteryPct = 50
} }
} }
/**
* 리스너에 의해 호출되는 UI 및 데이터 갱신 함수
*/
private fun refreshTorrentStats() { private fun refreshTorrentStats() {
serviceScope.launch { serviceScope.launch {
val vector = session.swig().get_torrents() val vector = session.swig().get_torrents()
@@ -444,24 +436,27 @@ var batteryPct = 50
val isPaused = status.flags().and_(libtorrent.getPaused()).nonZero() val isPaused = status.flags().and_(libtorrent.getPaused()).nonZero()
val isFinished = status.isFinished val isFinished = status.isFinished
val isDownloading = (state.swig() == torrent_status.state_t.downloading.swigValue()) val isDownloading = (state.swig() == torrent_status.state_t.downloading.swigValue())
val previewTag = getPreviewStatusTag(handle, hashStr, status)
val stateText = when { val stateText = when {
isFinished -> "완료" isFinished -> "완료"
!status.hasMetadata() -> "메타데이터 수신 중..." !status.hasMetadata() -> "메타데이터 수신 중..."
!isCharging -> "충전 대기 중" !isCharging -> "충전 대기 중$previewTag"
isDownloading -> "다운로드 중" isDownloading -> "다운로드 중$previewTag"
isPaused -> "일시정지" isPaused -> "일시정지$previewTag"
else -> "대기 중" else -> "대기 중$previewTag"
} }
tasks.add(TorrentTask( tasks.add(
infoHash = status.infoHash().toString(), TorrentTask(
name = displayName, infoHash = hashStr,
progress = status.progress() * 100f, name = displayName,
isPaused = isPaused, progress = status.progress() * 100f,
isQueued = !isPaused && !isFinished && !isDownloading, isPaused = isPaused,
stateText = stateText isQueued = !isPaused && !isFinished && !isDownloading,
)) stateText = stateText
)
)
} }
_torrentTasks.value = tasks _torrentTasks.value = tasks
@@ -475,27 +470,25 @@ var batteryPct = 50
return return
} }
// 1. 메타데이터 수신 중인 파일 수
val metadataCount = tasks.count { it.stateText == "메타데이터 수신 중..." } val metadataCount = tasks.count { it.stateText == "메타데이터 수신 중..." }
val downloadingTasks = tasks.filter { !it.isPaused && it.stateText.startsWith("다운로드 중") }
// 2. 실제 다운로드 중인 파일들 (충전/와이파이 조건으로 활성화된 것들)
val downloadingTasks = tasks.filter { it.isPaused == false }.filter { it.stateText == "다운로드 중" }
val downloadingCount = downloadingTasks.size val downloadingCount = downloadingTasks.size
// 3. 다운로드 중인 파일들의 평균 진행률
val averageProgress = if (downloadingTasks.isNotEmpty()) { val averageProgress = if (downloadingTasks.isNotEmpty()) {
downloadingTasks.map { it.progress }.average().toInt() downloadingTasks.map { it.progress }.average().toInt()
} else { } else {
0 0
} }
// 4. 전체 다운로드/업로드 속도 (Session에서 직접 가져옴)
val stats = session.stats() val stats = session.stats()
val downloadSpeed = formatSpeed(stats.downloadRate()) val downloadSpeed = formatSpeed(stats.downloadRate())
val uploadSpeed = formatSpeed(stats.uploadRate()) val uploadSpeed = formatSpeed(stats.uploadRate())
// 알림 메시지 구성 val title = if (downloadingCount > 0) {
val title = if (downloadingCount > 0) "총 ${tasks.size} | 다운 ${downloadingCount} | 메타 ${metadataCount} | 대기 ${tasks.size - (downloadingCount + metadataCount)}" else "대기 중" "총 ${tasks.size} | 다운 ${downloadingCount} | 메타 ${metadataCount} | 대기 ${tasks.size - (downloadingCount + metadataCount)}"
} else {
"대기 중"
}
val content = StringBuilder().apply { val content = StringBuilder().apply {
append("평균 다운 진행율 $averageProgress% | ") append("평균 다운 진행율 $averageProgress% | ")
append("↓ $downloadSpeed ↑ $uploadSpeed") append("↓ $downloadSpeed ↑ $uploadSpeed")
@@ -504,12 +497,11 @@ var batteryPct = 50
notificationBuilder notificationBuilder
.setContentTitle(title) .setContentTitle(title)
.setContentText(content) .setContentText(content)
.setProgress(100, averageProgress, downloadingCount == 0 && metadataCount > 0) // 메타 수신 중엔 불확정 게이지 .setProgress(100, averageProgress, downloadingCount == 0 && metadataCount > 0)
notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build()) notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build())
} }
// 속도 포맷팅 유틸리티
private fun formatSpeed(bytesPerSecond: Long): String { private fun formatSpeed(bytesPerSecond: Long): String {
val kb = bytesPerSecond / 1024.0 val kb = bytesPerSecond / 1024.0
return if (kb >= 1024) { return if (kb >= 1024) {
@@ -519,12 +511,11 @@ var batteryPct = 50
} }
} }
// --- 데이터 관리 및 이동 로직 (기존 유지) ---
@RequiresApi(Build.VERSION_CODES.Q) @RequiresApi(Build.VERSION_CODES.Q)
private fun moveToPrivateStorage(handle: TorrentHandle) { private fun moveToPrivateStorage(handle: TorrentHandle) {
try { try {
val status = handle.status() val status = handle.status()
val hashStr = status.infoHash().toString()
val torrentName = if (status.hasMetadata()) handle.torrentFile()?.name() ?: status.name() else status.name() val torrentName = if (status.hasMetadata()) handle.torrentFile()?.name() ?: status.name() else status.name()
val sourcePath = File(tempDir, torrentName) val sourcePath = File(tempDir, torrentName)
val destPath = File(File(getExternalFilesDir(null), "completed_torrents").apply { mkdirs() }, torrentName) val destPath = File(File(getExternalFilesDir(null), "completed_torrents").apply { mkdirs() }, torrentName)
@@ -535,26 +526,74 @@ var batteryPct = 50
sourcePath.deleteRecursively() sourcePath.deleteRecursively()
} }
session.remove(handle) session.remove(handle)
File(resumeDir, "${status.infoHash()}.resume").delete() previewPiecesMap.remove(hashStr)
File(resumeDir, "$hashStr.resume").delete()
File(resumeDir, "$hashStr.magnet").delete()
} }
} catch (e: Exception) { e.printStackTrace() } } catch (e: Exception) {
e.printStackTrace()
}
} }
private fun saveResumeFile(hash: String, params: AddTorrentParams) { private fun saveResumeFile(hash: String, params: AddTorrentParams) {
try { try {
val data = Vectors.byte_vector2bytes(libtorrent.write_resume_data_buf_ex(params.swig())) val data = Vectors.byte_vector2bytes(libtorrent.write_resume_data_buf_ex(params.swig()))
File(resumeDir, "$hash.resume").writeBytes(data) File(resumeDir, "$hash.resume").writeBytes(data)
} catch (e: Exception) { e.printStackTrace() } File(resumeDir, "$hash.magnet").delete()
} catch (e: Exception) {
e.printStackTrace()
}
} }
private fun restoreExistingDownloads() { private fun restoreExistingDownloads() {
val restoredHashes = mutableSetOf<String>()
// 1. 메타데이터가 확보된 기존 .resume 파일 먼저 복원
resumeDir.listFiles()?.filter { it.extension == "resume" }?.forEach { file -> resumeDir.listFiles()?.filter { it.extension == "resume" }?.forEach { file ->
try { try {
val data = file.readBytes() val data = file.readBytes()
val swigParams = libtorrent.read_resume_data_ex(Vectors.bytes2byte_vector(data), error_code()) val swigParams = libtorrent.read_resume_data_ex(Vectors.bytes2byte_vector(data), error_code())
swigParams.setSave_path(tempDir.absolutePath) 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) session.swig().async_add_torrent(swigParams)
} catch (e: Exception) { e.printStackTrace() } 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()
}
} }
} }
@@ -562,7 +601,6 @@ var batteryPct = 50
intent?.getStringExtra("EXTRA_MAGNET_URI")?.let { addMagnet(it) } intent?.getStringExtra("EXTRA_MAGNET_URI")?.let { addMagnet(it) }
intent?.getBooleanExtra("WIFI_STATE", false)?.let { intent?.getBooleanExtra("WIFI_STATE", false)?.let {
isWifiConnected = it isWifiConnected = it
} }
return START_STICKY return START_STICKY
} }
@@ -574,24 +612,36 @@ var batteryPct = 50
if (error.value() == 0) { if (error.value() == 0) {
swigParams.setSave_path(tempDir.absolutePath) swigParams.setSave_path(tempDir.absolutePath)
// 수동 제어를 위해 auto_managed 해제
var flags = swigParams.flags var flags = swigParams.flags
flags = flags.and_(libtorrent.getAuto_managed().inv()) flags = flags.and_(libtorrent.getAuto_managed().inv())
flags = flags.or_(libtorrent.getSequential_download())
swigParams.flags = flags swigParams.flags = flags
session.swig().async_add_torrent(swigParams) 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() updateSessionState()
} }
updateTrackers() updateTrackers()
} catch (e: Exception) { e.printStackTrace() } } catch (e: Exception) {
e.printStackTrace()
}
} }
private fun startForegroundService() { private fun startForegroundService() {
val channelId = "torrent_channel" val channelId = "torrent_channel"
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notificationManager.createNotificationChannel(NotificationChannel(channelId, "Torrent Service", NotificationManager.IMPORTANCE_LOW)) notificationManager.createNotificationChannel(
NotificationChannel(channelId, "Torrent Service", NotificationManager.IMPORTANCE_LOW)
)
} }
notificationBuilder = NotificationCompat.Builder(this, channelId) notificationBuilder = NotificationCompat.Builder(this, channelId)
.setSmallIcon(android.R.drawable.stat_sys_download) .setSmallIcon(android.R.drawable.stat_sys_download)
@@ -609,16 +659,15 @@ var batteryPct = 50
super.onDestroy() super.onDestroy()
try { try {
unregisterReceiver(batteryReceiver) unregisterReceiver(batteryReceiver)
} catch (e: Exception){e.printStackTrace()} } catch (e: Exception) {
e.printStackTrace()
}
serviceScope.cancel() serviceScope.cancel()
} }
fun resumeTorrent(infoHash: String) { fun resumeTorrent(infoHash: String) {
try { try {
session.find(Sha1Hash(infoHash))?.resume() session.find(Sha1Hash(infoHash))?.resume()
// 💡 UI 즉시 갱신: 수동 조작 시 답답하지 않게 바로 상태를 업데이트합니다.
refreshTorrentStats() refreshTorrentStats()
} catch (e: Exception) { } catch (e: Exception) {
e.printStackTrace() e.printStackTrace()
@@ -627,11 +676,7 @@ var batteryPct = 50
fun pauseTorrent(infoHash: String) { fun pauseTorrent(infoHash: String) {
try { try {
session.find(Sha1Hash(infoHash))?.let { session.find(Sha1Hash(infoHash))?.pause()
it.pause()
// 대기열 맨 뒤로 보내기 (선택 사항)
// it.queuePositionBottom()
}
refreshTorrentStats() refreshTorrentStats()
} catch (e: Exception) { } catch (e: Exception) {
e.printStackTrace() e.printStackTrace()
@@ -642,7 +687,6 @@ var batteryPct = 50
try { try {
val handle = session.find(Sha1Hash(infoHash)) val handle = session.find(Sha1Hash(infoHash))
if (handle != null) { if (handle != null) {
// 1. 실제 파일 삭제 (요청 시)
if (deleteFile) { if (deleteFile) {
val status = handle.status() val status = handle.status()
val torrentName = if (status.hasMetadata()) handle.torrentFile()?.name() ?: status.name() else status.name() val torrentName = if (status.hasMetadata()) handle.torrentFile()?.name() ?: status.name() else status.name()
@@ -651,22 +695,16 @@ var batteryPct = 50
targetFile.deleteRecursively() targetFile.deleteRecursively()
} }
} }
// 2. 엔진에서 세션 제거
session.remove(handle) session.remove(handle)
// 3. 리쥼(이어받기) 데이터 파일 삭제
val resumeFile = File(resumeDir, "$infoHash.resume")
if (resumeFile.exists()) {
resumeFile.delete()
}
// 💡 삭제 후 목록에서 즉시 사라지도록 UI 갱신
refreshTorrentStats()
} }
previewPiecesMap.remove(infoHash)
File(resumeDir, "$infoHash.resume").delete()
File(resumeDir, "$infoHash.magnet").delete()
refreshTorrentStats()
} catch (e: Exception) { } catch (e: Exception) {
e.printStackTrace() e.printStackTrace()
} }
} }
} }
+1
View File
@@ -25,5 +25,6 @@ rootProject.name = "LunarLauncher"
include ("app") include ("app")
include(":core:core-common") include(":core:core-common")
include(":core:core-network") include(":core:core-network")
include(":feature:feature-torrent")
include(":gdrive") include(":gdrive")
include(":lun_launcher") include(":lun_launcher")