package kr.co.itosm.dutycalendar import android.app.job.JobInfo import android.app.job.JobScheduler import android.content.ComponentName import android.content.Context import android.net.ConnectivityManager import android.net.Network import android.net.NetworkCapabilities import android.security.keystore.KeyGenParameterSpec import android.security.keystore.KeyProperties import android.util.AtomicFile import android.util.Base64 import org.json.JSONObject import java.io.File import java.io.ByteArrayOutputStream import java.net.URL import java.security.KeyStore import java.util.concurrent.Executors import java.util.concurrent.atomic.AtomicInteger import javax.crypto.Cipher import javax.crypto.KeyGenerator import javax.crypto.SecretKey import javax.crypto.spec.GCMParameterSpec import javax.net.ssl.HttpsURLConnection /** * 인증값은 안드로이드 키 저장소의 키로 암호화한 뒤 백업 제외 영역에 보관한다. * APK나 일반 설정 및 화면 로그에는 인증값을 넣지 않는다. 사용자가 웹 연동을 선택하고 홈페이지 회원으로 로그인한 경우에만 전송한다. * 앱 화면이 열려 있을 때 변경을 기다리는 연결을 유지한다. 화면을 닫으면 예약 작업으로 전환한다. */ object SyncClient { const val WEB_URL = "https://duty.itosm.co.kr/calendar/" private const val KEY = "duty-calendar-connection-v1" private val executor = Executors.newSingleThreadExecutor() private val generation = AtomicInteger(0) @Volatile private var watchConnection: HttpsURLConnection? = null @Volatile var message = "이 기기에 저장" private set @Volatile private var observer: (() -> Unit)? = null private var connectivity: ConnectivityManager? = null private var networkCallback: ConnectivityManager.NetworkCallback? = null private fun file(context: Context) = AtomicFile(File(context.noBackupFilesDir, "calendar-connection")) private fun key(): SecretKey { val store = KeyStore.getInstance("AndroidKeyStore").apply { load(null) } (store.getKey(KEY, null) as? SecretKey)?.let { return it } return KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore").apply { init(KeyGenParameterSpec.Builder(KEY, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT).setBlockModes(KeyProperties.BLOCK_MODE_GCM).setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE).build()) }.generateKey() } @Synchronized private fun token(context: Context): String? = runCatching { val saved = JSONObject(file(context).openRead().bufferedReader().use { it.readText() }) val cipher = Cipher.getInstance("AES/GCM/NoPadding") cipher.init(Cipher.DECRYPT_MODE, key(), GCMParameterSpec(128, Base64.decode(saved.getString("iv"), Base64.NO_WRAP))) cipher.doFinal(Base64.decode(saved.getString("value"), Base64.NO_WRAP)).toString(Charsets.UTF_8) }.getOrNull() private fun remember(context: Context, value: String) { val cipher = Cipher.getInstance("AES/GCM/NoPadding").apply { init(Cipher.ENCRYPT_MODE, key()) } val saved = JSONObject().put("iv", Base64.encodeToString(cipher.iv, Base64.NO_WRAP)).put("value", Base64.encodeToString(cipher.doFinal(value.toByteArray()), Base64.NO_WRAP)) val target = file(context); val output = target.startWrite() try { output.write(saved.toString().toByteArray()); target.finishWrite(output) } catch (error: Exception) { target.failWrite(output); throw error } } fun enabled(context: Context) = context.getSharedPreferences("web_sync", Context.MODE_PRIVATE).getBoolean("enabled", false) fun connected(context: Context) = enabled(context) && token(context) != null fun memberName(context: Context) = context.getSharedPreferences("web_sync", Context.MODE_PRIVATE).getString("member_name", "회원").orEmpty() fun disable(context: Context) { // 먼저 동의를 해제한다. 이미 대기 중인 작업도 다음 전송 전에 이 값을 확인한다. // 서버 자료와 기기 일정은 지우지 않으므로 연동을 꺼도 위젯과 기기 편집은 계속 사용할 수 있다. val previous = token(context) context.getSharedPreferences("web_sync", Context.MODE_PRIVATE).edit().putBoolean("enabled", false).commit() background(); context.getSystemService(JobScheduler::class.java).apply { cancel(2102); cancel(2103) } file(context).delete(); message = "웹 연동 꺼짐 · 이 기기에 저장" DutyWidget.updateAll(context) Reminders.reschedule(context) if (previous != null) executor.execute { runCatching { request(context.applicationContext, "logout", JSONObject(), tokenOverride = previous) } } } private fun expire(context: Context) { // 인증이 끝난 뒤에는 회원용 근무표를 표시하지 않는다. 개인 자료는 재로그인을 위해 보관한다. file(context).delete() context.getSystemService(JobScheduler::class.java).apply { cancel(2102); cancel(2103) } DutyWidget.updateAll(context) Reminders.reschedule(context) } private class ServerError(val status: Int, message: String) : Exception(message) private fun request(context: Context, path: String, body: JSONObject? = null, watch: Boolean = false, tokenOverride: String? = null): JSONObject { val connection = URL(WEB_URL + "api/" + path).openConnection() as HttpsURLConnection if (watch) watchConnection = connection try { connection.connectTimeout = 8000; connection.readTimeout = if (watch) 32000 else 15000 connection.instanceFollowRedirects = false connection.setRequestProperty("X-Duty-Request", "1") (tokenOverride ?: token(context))?.let { connection.setRequestProperty("Authorization", "Bearer $it") } if (body != null) { connection.requestMethod = "POST"; connection.doOutput = true connection.setRequestProperty("Content-Type", "application/json; charset=utf-8") connection.outputStream.use { it.write(body.toString().toByteArray(Charsets.UTF_8)) } } val status = connection.responseCode val stream = if (status in 200..299) connection.inputStream else connection.errorStream val bytes = ByteArrayOutputStream().apply { stream?.use { input -> val buffer = ByteArray(8192) while (true) { val count = input.read(buffer) if (count < 0) break check(size() + count <= 16 * 1024 * 1024) { "일정 자료가 너무 큽니다." } write(buffer, 0, count) } } }.toByteArray() val response = JSONObject(bytes.toString(Charsets.UTF_8)) if (status !in 200..299) throw ServerError(status, response.optString("detail", "연결 상태를 확인해 주세요.")) return response } finally { connection.disconnect(); if (watch && watchConnection === connection) watchConnection = null } } private fun publish(value: String) { message = value; observer?.invoke() } private fun perform(context: Context, force: Boolean = false): Boolean { if (!connected(context)) { publish("이 기기에 저장"); return true } return try { val operations = PlannerStore.operations(context) var received = false if (operations.length() > 0) { val result = request(context, "mutations", JSONObject().put("operations", operations)) if (!connected(context)) return true PlannerStore.accept(context, result.getJSONObject("state"), result) received = true } else if (RefreshPolicy.needsRefresh(PlannerStore.refreshedAt(context), System.currentTimeMillis(), force)) { val result = request(context, "state") if (!connected(context)) return true PlannerStore.accept(context, result) received = true } publish(when { PlannerStore.conflictCount(context) > 0 -> "동시 수정 내용 확인 필요"; PlannerStore.pendingCount(context) > 0 -> "기기에 저장 · 서버 전송 대기"; received -> "서버와 저장 내용이 일치합니다."; else -> "서버 저장 완료 · 변경 시 갱신" }) schedulePending(context) true } catch (error: Exception) { if (error is ServerError && error.status in listOf(401, 403)) expire(context) schedulePending(context) publish(if (error is ServerError && error.status in listOf(400, 401, 403, 409, 429)) error.message ?: "연결 확인 필요" else "연결 대기 · 기기에 저장됨") false } } fun sync(context: Context, force: Boolean = false, complete: (Boolean) -> Unit = {}) { val app = context.applicationContext executor.execute { complete(perform(app, force)) } } fun connect(context: Context, username: String, password: String, complete: (String?) -> Unit) { val app = context.applicationContext executor.execute { try { val result = request(app, "login", JSONObject().put("kind", "android").put("username", username).put("password", password).put("expectedCalendar", PlannerStore.calendarId(app))) val value = result.getString("token") val remote = request(app, "state", tokenOverride = value) val previous = PlannerStore.calendarId(app) if (previous.isNotBlank() && previous != remote.getString("calendarId")) throw ServerError(400, "원래 일정을 사용하던 회원으로 로그인해 주세요. 기존 일정은 보관했습니다.") remember(app, value) app.getSharedPreferences("web_sync", Context.MODE_PRIVATE).edit().putBoolean("enabled", true).putString("member_name", result.getJSONObject("member").getString("displayName")).commit() PlannerStore.accept(app, remote) schedule(app); perform(app); complete(null) } catch (error: Exception) { complete(if (error is ServerError) error.message else "서버에 연결하지 못했습니다. 인터넷 연결을 확인해 주세요.") } } } fun foreground(context: Context, callback: () -> Unit) { val app = context.applicationContext observer = callback; sync(app) // 끊어진 장기 연결의 시간 만료를 기다리지 않도록 실제 네트워크 복구 알림에서도 재시도한다. // 검증된 네트워크로 바뀔 때 한 번만 요청해 신호 세기 변경마다 중복 전송하지 않는다. networkCallback?.let { old -> runCatching { connectivity?.unregisterNetworkCallback(old) } } connectivity = app.getSystemService(ConnectivityManager::class.java) networkCallback = object : ConnectivityManager.NetworkCallback() { private var validated: Network? = null override fun onAvailable(network: Network) { watchConnection?.disconnect() } override fun onCapabilitiesChanged(network: Network, capabilities: NetworkCapabilities) { if (capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED) && network != validated) { validated = network; sync(app); watchConnection?.disconnect() } } override fun onLost(network: Network) { if (validated == network) validated = null watchConnection?.disconnect() publish("연결 대기 · 기기에 저장됨") } }.also { connectivity?.registerDefaultNetworkCallback(it) } val current = generation.incrementAndGet() watchConnection?.disconnect() Thread({ while (generation.get() == current) { if (!connected(app)) { Thread.sleep(2000); continue } try { if (PlannerStore.operations(app).length() > 0 && !executor.submit { perform(app) }.get()) { Thread.sleep(4000) continue } val change = request(app, "changes?after=${PlannerStore.revision(app)}&company_after=${PlannerStore.companyVersion(app)}", watch = true) // 최신 자료를 받기 전 같은 알림으로 요청이 쌓이지 않도록 직렬 동기화가 끝날 때까지 기다린다. if (generation.get() == current && (change.getLong("revision") != PlannerStore.revision(app) || change.optString("companyVersion") != PlannerStore.companyVersion(app) || PlannerStore.operations(app).length() > 0)) executor.submit { perform(app, true) }.get() } catch (error: Exception) { if (error is ServerError && error.status in listOf(401, 403)) { expire(app); publish("회원 로그인을 다시 확인해 주세요."); break } if (generation.get() == current) Thread.sleep(4000) } } }, "calendar-changes").start() } fun background() { observer = null; generation.incrementAndGet(); watchConnection?.disconnect() networkCallback?.let { callback -> runCatching { connectivity?.unregisterNetworkCallback(callback) } } networkCallback = null } fun schedule(context: Context) { if (!connected(context)) return val scheduler = context.getSystemService(JobScheduler::class.java) // 기존 15분 작업은 월별 작업으로 한 번 교체한다. 앱을 열 때마다 주기 시작점을 다시 잡지 않는다. val job = scheduler.getPendingJob(2102) if (job?.intervalMillis != RefreshPolicy.MONTH_MS || job.flexMillis != RefreshPolicy.FLEX_MS) { scheduler.cancel(2102) scheduler.schedule(JobInfo.Builder(2102, ComponentName(context, PlannerSyncService::class.java)) .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY).setPeriodic(RefreshPolicy.MONTH_MS, RefreshPolicy.FLEX_MS).setPersisted(true).build()) } } private fun schedulePending(context: Context) { val scheduler = context.getSystemService(JobScheduler::class.java) // 오프라인에서 작성한 변경은 월별 갱신까지 묶어 두지 않는다. 전송할 변경이 있을 때만 한 번 예약한다. if (!connected(context) || PlannerStore.operations(context).length() == 0) { scheduler.cancel(2103); return } if (scheduler.getPendingJob(2103) == null) scheduler.schedule(JobInfo.Builder(2103, ComponentName(context, PlannerSyncService::class.java)) .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY).setMinimumLatency(30_000L).setPersisted(true).build()) } }