당직근무 0.10.0 소스와 위젯 꾸미기 및 제작 매뉴얼 공개
위젯별 투명도와 밝은·어두운 색상 및 글자 크기와 표시 항목을 추가했다. 모든 위젯에 함께 적용하는 기본값과 개별 설정을 구분하고 크기에 따라 배치를 바꾼다. 포럼에 APK와 전체 소스 및 사용법과 제작 매뉴얼을 함께 배포한다. 앱 단위 검사 34개와 서버 검사 63개 및 웹 날짜·업데이트 검사 통과. 공개 소스에서 APK 빌드와 정적 검사 오류 0개 확인. 경고는 69개다. Android 16 가상 기기에서 기존 앱 위에 설치하고 투명 위젯과 큰 글자 및 RemoteViews 검사를 확인했다. 실제 휴대폰과 다른 홈 화면 앱의 절전·크기 동작은 별도 확인이 필요하다. 회원 DB와 인증 정보 및 배포 서명 키와 내부 운영 기록은 공개 자료에 포함하지 않았다.
This commit is contained in:
commit
8112721fa8
96 files changed
+7495
No files matched your search
@@ -0,0 +1,27 @@
|
||||
package kr.co.itosm.dutycalendar
|
||||
|
||||
import android.content.Context
|
||||
import org.json.JSONObject
|
||||
import java.time.LocalDate
|
||||
|
||||
/** 기념일 원본은 회원 캘린더에 보관한다. 소속 공유 목록에서는 읽지 않는다. */
|
||||
object Anniversaries {
|
||||
const val HELP = "매년 반복됩니다. 양력 2월 29일과 음력 30일이 없는 해에는 그달 말일에 표시합니다. 윤달이 없는 해에는 같은 일반 월에 표시합니다. 음력은 1900~2050년 자료를 사용합니다."
|
||||
fun rule(data: JSONObject) = AnniversaryRule(data.getString("calendar"), data.getInt("month"), data.getInt("day"), data.getBoolean("leapMonth"))
|
||||
fun validate(data: JSONObject) {
|
||||
require(data.getString("title").trim().length in 1..60) { "기념일 이름은 1~60자로 입력해 주세요." }
|
||||
require(data.getString("category") in listOf("BIRTHDAY", "ANNIVERSARY")) { "기념일 종류를 선택해 주세요." }
|
||||
require(data.getString("notes").length <= 1000) { "메모는 1000자까지 입력할 수 있습니다." }
|
||||
require(data.optInt("reminderMinutes",-1) in Reminders.minutes) { "알림 시간을 확인해 주세요." }
|
||||
rule(data)
|
||||
}
|
||||
fun all(context: Context) = if (SyncClient.connected(context)) PlannerStore.items(context).filter { it.getString("kind") == "anniversary" }
|
||||
.sortedBy { it.getJSONObject("data").getString("title") } else emptyList()
|
||||
fun on(context: Context, date: LocalDate): List<JSONObject> {
|
||||
val lunar by lazy { LunarDates.day(context, date) }
|
||||
return all(context).filter { item -> runCatching {
|
||||
val rule = rule(item.getJSONObject("data")); rule.matches(date, if (rule.calendar == "LUNAR") lunar else null)
|
||||
}.getOrDefault(false) }
|
||||
}
|
||||
fun description(data: JSONObject) = "${if (data.getString("category") == "BIRTHDAY") "생일" else "기념일"} · ${rule(data).description()}"
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package kr.co.itosm.dutycalendar
|
||||
|
||||
import android.app.Activity
|
||||
import android.app.AlertDialog
|
||||
import android.text.InputFilter
|
||||
import android.text.InputType
|
||||
import android.view.View
|
||||
import android.widget.*
|
||||
import org.json.JSONObject
|
||||
import java.time.LocalDate
|
||||
import java.util.UUID
|
||||
|
||||
/** 회원의 생일과 기념일을 별도로 편집한다. 저장 성공과 서버 전송 완료를 구분해서 안내한다. */
|
||||
class AnniversaryDialogs(private val activity: Activity, private val changed: () -> Unit) {
|
||||
private fun dp(n: Int) = (n * activity.resources.displayMetrics.density).toInt()
|
||||
fun list() {
|
||||
if (!SyncClient.connected(activity)) { Toast.makeText(activity, "기념일은 회원 로그인 후 사용할 수 있습니다.", Toast.LENGTH_LONG).show(); return }
|
||||
val items = Anniversaries.all(activity)
|
||||
val builder = AlertDialog.Builder(activity).setTitle("내 생일·기념일")
|
||||
.setPositiveButton("추가") { _, _ -> edit() }.setNegativeButton("닫기", null)
|
||||
if (items.isEmpty()) builder.setMessage("생일과 기념일을 등록하면 매년 달력에 표시됩니다.\n\n내 계정에만 보관하며 같은 계정으로 다시 로그인하면 복원합니다.")
|
||||
else builder.setItems(items.map { "${it.getJSONObject("data").getString("title")}\n${Anniversaries.description(it.getJSONObject("data"))}" }.toTypedArray()) { _, index -> edit(items[index]) }
|
||||
builder.show()
|
||||
}
|
||||
fun edit(item: JSONObject? = null) {
|
||||
if (!SyncClient.connected(activity)) { list(); return }
|
||||
val data = item?.getJSONObject("data")
|
||||
val form = LinearLayout(activity).apply { orientation = LinearLayout.VERTICAL; setPadding(dp(20), dp(8), dp(20), dp(16)) }
|
||||
fun caption(value: String) { form.addView(TextView(activity).apply { text=value; textSize=13f; setPadding(0,dp(12),0,dp(6)) }) }
|
||||
fun selector(label: String, values: List<String>, index: Int): Spinner {
|
||||
caption(label)
|
||||
return Spinner(activity).apply { adapter=ArrayAdapter(activity,android.R.layout.simple_spinner_dropdown_item,values);setSelection(index);contentDescription=label;form.addView(this) }
|
||||
}
|
||||
caption("기념일 이름")
|
||||
val title = EditText(activity).apply { setSingleLine(true);hint="예: 내 생일 · 결혼기념일";contentDescription="기념일 이름";filters=arrayOf(InputFilter.LengthFilter(60));setText(data?.optString("title").orEmpty()) };form.addView(title)
|
||||
val category=selector("종류",listOf("생일","기념일"),if(data?.optString("category")=="ANNIVERSARY")1 else 0)
|
||||
val calendar=selector("날짜 기준",listOf("양력","음력"),if(data?.optString("calendar")=="LUNAR")1 else 0)
|
||||
val month=selector("월",(1..12).map{"${it}월"},(data?.optInt("month")?:LocalDate.now().monthValue)-1)
|
||||
val day=selector("일",(1..31).map{"${it}일"},(data?.optInt("day")?:LocalDate.now().dayOfMonth)-1)
|
||||
val leap=CheckBox(activity).apply { text="음력 윤달";isChecked=data?.optBoolean("leapMonth")?:false;minHeight=dp(48) };form.addView(leap)
|
||||
calendar.onItemSelectedListener=object:AdapterView.OnItemSelectedListener {
|
||||
override fun onNothingSelected(parent:AdapterView<*>?)=Unit
|
||||
override fun onItemSelected(parent:AdapterView<*>?,view:View?,position:Int,id:Long){leap.visibility=if(position==1)View.VISIBLE else View.GONE;if(position==0)leap.isChecked=false}
|
||||
}
|
||||
caption(Anniversaries.HELP)
|
||||
val reminder=selector("휴대폰 알림",Reminders.labels,Reminders.minutes.indexOf(data?.optInt("reminderMinutes",-1)?:-1).coerceAtLeast(0))
|
||||
caption("기념일 오전 9시를 기준으로 알립니다. 휴대폰 알림 허용이 필요하며 절전 중에는 늦게 전달될 수 있습니다.")
|
||||
caption("메모")
|
||||
val notes=EditText(activity).apply { inputType=InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_MULTI_LINE;minLines=2;filters=arrayOf(InputFilter.LengthFilter(1000));setText(data?.optString("notes").orEmpty()) };form.addView(notes)
|
||||
caption("내 계정에만 저장됩니다. 인터넷이 끊기면 기기에 보관한 뒤 다시 연결될 때 서버로 전송합니다. 재설치 전 서버 저장 완료를 확인해 주세요.")
|
||||
if(item!=null)form.addView(Button(activity).apply{text="휴대폰 달력에 보내기";setOnClickListener{DeviceCalendar.sendAnniversary(activity,item)}})
|
||||
if(item!=null)caption("저장된 기념일의 다음 날짜 한 번을 달력 앱으로 보냅니다. 매년 음력 계산은 당직근무에서 계속합니다.")
|
||||
val error=TextView(activity).apply{setTextColor(0xFFB24D52.toInt())};form.addView(error)
|
||||
val builder=AlertDialog.Builder(activity).setTitle(if(item==null)"생일·기념일 추가" else "생일·기념일 수정")
|
||||
.setView(ScrollView(activity).apply{addView(form)}).setPositiveButton("저장",null).setNegativeButton("취소",null)
|
||||
if(item!=null)builder.setNeutralButton("삭제",null)
|
||||
val dialog=builder.create()
|
||||
dialog.setOnShowListener {
|
||||
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener {
|
||||
runCatching {
|
||||
val draft=JSONObject().put("title",title.text.toString().trim()).put("category",if(category.selectedItemPosition==0)"BIRTHDAY" else "ANNIVERSARY")
|
||||
.put("calendar",if(calendar.selectedItemPosition==0)"SOLAR" else "LUNAR").put("month",month.selectedItemPosition+1).put("day",day.selectedItemPosition+1)
|
||||
.put("leapMonth",calendar.selectedItemPosition==1&&leap.isChecked).put("notes",notes.text.toString())
|
||||
.put("reminderMinutes",Reminders.minutes[reminder.selectedItemPosition])
|
||||
PlannerStore.put(activity,item?.getString("id")?:UUID.randomUUID().toString(),"anniversary",draft)
|
||||
}.onSuccess { SyncClient.sync(activity);changed();dialog.dismiss();Toast.makeText(activity,"기기에 저장했습니다. 서버 저장 상태는 화면 위에서 확인하세요.",Toast.LENGTH_LONG).show();if(Reminders.minutes[reminder.selectedItemPosition]>=0)Reminders.requestPermission(activity) }
|
||||
.onFailure{error.text=it.message?:"입력 내용을 확인해 주세요."}
|
||||
}
|
||||
if(item!=null)dialog.getButton(AlertDialog.BUTTON_NEUTRAL).setOnClickListener {
|
||||
AlertDialog.Builder(activity).setTitle("이 기념일을 삭제할까요?").setMessage("내 계정의 앱과 웹에도 반영됩니다.")
|
||||
.setNegativeButton("취소",null).setPositiveButton("삭제"){_,_->
|
||||
runCatching{PlannerStore.put(activity,item.getString("id"),"anniversary",JSONObject(),true)}
|
||||
.onSuccess{SyncClient.sync(activity);changed();dialog.dismiss()}.onFailure{error.text=it.message}
|
||||
}.show()
|
||||
}
|
||||
};dialog.show()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package kr.co.itosm.dutycalendar
|
||||
|
||||
import java.time.LocalDate
|
||||
import java.time.YearMonth
|
||||
|
||||
/** 매년 반복하는 기념일의 날짜 규칙이다. 양력과 한국 음력을 서로 바꿔 저장하지 않는다.
|
||||
* 양력 2월 29일은 평년에 2월 말일로 표시한다. 음력 30일도 해당 달이 29일까지면 말일로 표시한다.
|
||||
* 윤달 기념일은 같은 윤달이 있는 해에는 윤달에만 표시한다. 없는 해에는 같은 일반 월을 사용한다.
|
||||
* 화면에서 이 기준을 알려 주며 음력 자료 범위를 벗어나면 날짜를 추정하지 않는다.
|
||||
*/
|
||||
data class AnniversaryRule(val calendar: String, val month: Int, val day: Int, val leapMonth: Boolean = false) {
|
||||
init {
|
||||
require(calendar in listOf("SOLAR", "LUNAR") && month in 1..12) { "양력·음력과 월을 확인해 주세요." }
|
||||
val maximum = if (calendar == "LUNAR") 30 else YearMonth.of(2000, month).lengthOfMonth()
|
||||
require(day in 1..maximum && (calendar == "LUNAR" || !leapMonth)) { "날짜와 윤달 선택을 확인해 주세요." }
|
||||
}
|
||||
fun matches(date: LocalDate, lunar: LunarDay? = null): Boolean {
|
||||
if (calendar == "SOLAR") return date.monthValue == month && date.dayOfMonth == minOf(day, YearMonth.from(date).lengthOfMonth())
|
||||
lunar ?: return false
|
||||
val wantedLeap = leapMonth && lunar.yearHasLeapMonth
|
||||
return lunar.month == month && lunar.leap == wantedLeap && lunar.day == (lunar.length?.let { minOf(day, it) } ?: day)
|
||||
}
|
||||
fun description() = "${if (calendar == "SOLAR") "양력" else "음력"} ${if (leapMonth) "윤" else ""}${month}월 ${day}일 · 매년"
|
||||
}
|
||||
|
||||
data class LunarMonth(val start: Long, val month: Int, val leap: Boolean, val year: Int)
|
||||
data class LunarDay(val month: Int, val day: Int, val leap: Boolean, val length: Int?, val yearHasLeapMonth: Boolean)
|
||||
|
||||
/** 월 시작일 표에서 해당 음력 날짜와 그해 윤달 유무를 함께 구한다. */
|
||||
class LunarTable(private val rows: List<LunarMonth>) {
|
||||
private val leapMonths = rows.filter { it.leap }.map { it.year to it.month }.toSet()
|
||||
fun day(date: LocalDate): LunarDay? {
|
||||
if (date < LocalDate.of(1900, 1, 1) || date > LocalDate.of(2050, 12, 31)) return null
|
||||
val found = rows.binarySearchBy(date.toEpochDay()) { it.start }
|
||||
val index = if (found >= 0) found else -found - 2
|
||||
if (index < 0) return null
|
||||
val row = rows[index]
|
||||
return LunarDay(row.month, (date.toEpochDay() - row.start + 1).toInt(), row.leap,
|
||||
rows.getOrNull(index + 1)?.let { (it.start - row.start).toInt() }, (row.year to row.month) in leapMonths)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
package kr.co.itosm.dutycalendar
|
||||
|
||||
import android.app.PendingIntent
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageInfo
|
||||
import android.content.pm.PackageInstaller
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Build
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.net.URL
|
||||
import java.security.MessageDigest
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
import javax.net.ssl.HttpsURLConnection
|
||||
|
||||
/**
|
||||
* 업데이트는 사용자가 동의한 버전만 내려받는다. 외부 주소나 파일 경로를 입력받지 않는다.
|
||||
* 크기와 해시뿐 아니라 앱 식별자와 기존 서명까지 검사해야 다른 앱이나 변조된 파일을 설치하지 않는다.
|
||||
* 설치는 시스템의 정식 세션으로 요청한다. 자동 적용을 지원하지 않는 기기는 시스템 확인으로 이어진다.
|
||||
*/
|
||||
object AppUpdate {
|
||||
data class Release(val code: Long, val name: String, val bytes: Long, val sha256: String) {
|
||||
fun json() = JSONObject().put("appVersionCode", code).put("appVersion", name).put("apkBytes", bytes).put("apkSha256", sha256)
|
||||
}
|
||||
private val busy = AtomicBoolean(false)
|
||||
@Volatile var phase = "idle"; private set
|
||||
@Volatile var message = ""; private set
|
||||
@Volatile var percent = 0; private set
|
||||
@Volatile var release: Release? = null; private set
|
||||
@Volatile var confirmation: Intent? = null; private set
|
||||
private fun prefs(context: Context) = context.getSharedPreferences("app_install", Context.MODE_PRIVATE)
|
||||
fun file(context: Context) = File(context.cacheDir, "app-updates/update.apk")
|
||||
fun parse(json: JSONObject): Release {
|
||||
val code = json.getLong("appVersionCode")
|
||||
val name = json.getString("appVersion")
|
||||
val size = json.getLong("apkBytes")
|
||||
val hash = json.getString("apkSha256")
|
||||
require(code > 0 && name.matches(Regex("[0-9]+\\.[0-9]+\\.[0-9]+")))
|
||||
require(size in 1..67_108_864 && hash.matches(Regex("[a-f0-9]{64}")))
|
||||
return Release(code, name, size, hash)
|
||||
}
|
||||
@Suppress("DEPRECATION")
|
||||
fun code(info: PackageInfo) = if (Build.VERSION.SDK_INT >= 28) info.longVersionCode else info.versionCode.toLong()
|
||||
@Suppress("DEPRECATION")
|
||||
fun installed(context: Context) = code(context.packageManager.getPackageInfo(context.packageName, 0))
|
||||
fun pending(context: Context): Release? = runCatching { parse(JSONObject(prefs(context).getString("release", "")!!)) }.getOrNull()?.takeIf { it.code > installed(context) }
|
||||
private fun hash(file: File): String {
|
||||
val digest = MessageDigest.getInstance("SHA-256")
|
||||
file.inputStream().use { input ->
|
||||
val buffer = ByteArray(32768)
|
||||
while (true) { val count = input.read(buffer); if (count < 0) break; digest.update(buffer, 0, count) }
|
||||
}
|
||||
return digest.digest().joinToString("") { "%02x".format(it) }
|
||||
}
|
||||
@Suppress("DEPRECATION")
|
||||
private fun signatures(info: PackageInfo): Set<String> {
|
||||
val certificates = if (Build.VERSION.SDK_INT >= 28) info.signingInfo?.apkContentsSigners else info.signatures
|
||||
return certificates.orEmpty().map { MessageDigest.getInstance("SHA-256").digest(it.toByteArray()).joinToString("") { byte -> "%02x".format(byte) } }.toSet()
|
||||
}
|
||||
@Suppress("DEPRECATION")
|
||||
internal fun validate(context: Context, target: File, release: Release) {
|
||||
check(target.length() == release.bytes && hash(target) == release.sha256) { "설치 파일 검증에 실패했습니다. 다시 내려받아 주세요." }
|
||||
val flags = if (Build.VERSION.SDK_INT >= 28) PackageManager.GET_SIGNING_CERTIFICATES else PackageManager.GET_SIGNATURES
|
||||
val candidate = context.packageManager.getPackageArchiveInfo(target.path, flags)
|
||||
?: error("올바른 설치 파일이 아닙니다.")
|
||||
val current = context.packageManager.getPackageInfo(context.packageName, flags)
|
||||
check(candidate.packageName == context.packageName && code(candidate) == release.code && release.code > code(current)) { "이 앱의 새 버전인지 확인할 수 없습니다." }
|
||||
val signature = signatures(current)
|
||||
check(signature.isNotEmpty() && signatures(candidate) == signature) { "기존 앱과 제작 서명이 다릅니다. 설치를 중단했습니다." }
|
||||
}
|
||||
fun start(context: Context, wanted: Release) {
|
||||
if (!busy.compareAndSet(false, true)) return
|
||||
val app = context.applicationContext
|
||||
release = wanted; confirmation = null; phase = "downloading"; message = "새 버전을 내려받고 있습니다."; percent = 0
|
||||
prefs(app).edit().putString("release", wanted.json().toString()).apply()
|
||||
Thread({
|
||||
val target = file(app)
|
||||
target.parentFile!!.mkdirs()
|
||||
val temporary = File(target.parentFile, "update.part")
|
||||
var connection: HttpsURLConnection? = null
|
||||
try {
|
||||
if (!runCatching { validate(app, target, wanted) }.isSuccess) {
|
||||
connection = URL(SyncClient.WEB_URL + "download?version=" + wanted.code).openConnection() as HttpsURLConnection
|
||||
connection.connectTimeout = 15000; connection.readTimeout = 20000
|
||||
connection.instanceFollowRedirects = false
|
||||
check(connection.responseCode == 200) { "새 버전 정보를 다시 확인해 주세요." }
|
||||
val advertised = connection.contentLengthLong
|
||||
check(advertised < 0 || advertised == wanted.bytes) { "배포 파일이 변경됐습니다. 업데이트 확인을 다시 눌러 주세요." }
|
||||
connection.inputStream.use { input -> temporary.outputStream().use { output ->
|
||||
val buffer = ByteArray(32768); var written = 0L
|
||||
while (true) {
|
||||
val count = input.read(buffer); if (count < 0) break
|
||||
written += count
|
||||
check(written <= wanted.bytes) { "설치 파일 크기가 맞지 않습니다." }
|
||||
output.write(buffer, 0, count); percent = (written * 100 / wanted.bytes).toInt()
|
||||
}
|
||||
} }
|
||||
validate(app, temporary, wanted)
|
||||
check(!target.exists() || target.delete()) { "이전 임시 파일을 교체하지 못했습니다." }
|
||||
check(temporary.renameTo(target)) { "설치 파일을 저장하지 못했습니다." }
|
||||
}
|
||||
percent = 100; message = "내려받기와 파일 검증을 마쳤습니다."; phase = "ready"
|
||||
} catch (error: Exception) {
|
||||
temporary.delete()
|
||||
message = if (error is IllegalStateException) error.message.orEmpty() else "연결을 확인한 뒤 다시 시도해 주세요. 기존 일정은 그대로입니다."
|
||||
phase = "error"
|
||||
} finally { connection?.disconnect(); busy.set(false) }
|
||||
}, "app-download").start()
|
||||
}
|
||||
fun install(context: Context) {
|
||||
if (phase != "ready" || !busy.compareAndSet(false, true)) return
|
||||
val app = context.applicationContext
|
||||
val wanted = release ?: run { busy.set(false); return }
|
||||
phase = "installing"; message = "업데이트를 적용하고 있습니다. 완료되면 앱을 다시 열어 주세요."
|
||||
Thread({
|
||||
val installer = app.packageManager.packageInstaller
|
||||
var sessionId = -1
|
||||
try {
|
||||
validate(app, file(app), wanted)
|
||||
// 이전에 취소되거나 프로세스가 종료된 이 앱의 설치 세션만 정리한다.
|
||||
val previous = prefs(app).getInt("session", -1)
|
||||
if (previous >= 0) runCatching { installer.abandonSession(previous) }
|
||||
val params = PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL).apply {
|
||||
setAppPackageName(app.packageName); setSize(wanted.bytes)
|
||||
if (Build.VERSION.SDK_INT >= 31) setRequireUserAction(PackageInstaller.SessionParams.USER_ACTION_NOT_REQUIRED)
|
||||
}
|
||||
sessionId = installer.createSession(params)
|
||||
prefs(app).edit().putInt("session", sessionId).commit()
|
||||
val result = Intent(app, UpdateInstallReceiver::class.java).setAction(app.packageName + ".INSTALL_RESULT")
|
||||
// 시스템이 결과 상태를 채워야 하므로 변경 가능한 PendingIntent를 쓴다. 수신 대상을 앱 내부로 고정한다.
|
||||
val flags = PendingIntent.FLAG_UPDATE_CURRENT or if (Build.VERSION.SDK_INT >= 31) PendingIntent.FLAG_MUTABLE else 0
|
||||
val sender = PendingIntent.getBroadcast(app, sessionId, result, flags).intentSender
|
||||
installer.openSession(sessionId).use { session ->
|
||||
session.openWrite("base.apk", 0, wanted.bytes).use { output -> file(app).inputStream().use { it.copyTo(output) }; session.fsync(output) }
|
||||
session.commit(sender)
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
if (sessionId >= 0) runCatching { installer.abandonSession(sessionId) }
|
||||
message = "설치 요청을 완료하지 못했습니다. 다시 시도해 주세요."; phase = "error"
|
||||
} finally { busy.set(false) }
|
||||
}, "app-install").start()
|
||||
}
|
||||
internal fun result(context: Context, intent: Intent) {
|
||||
if (intent.getIntExtra(PackageInstaller.EXTRA_SESSION_ID, -2) != prefs(context).getInt("session", -1)) return
|
||||
when (intent.getIntExtra(PackageInstaller.EXTRA_STATUS, PackageInstaller.STATUS_FAILURE)) {
|
||||
PackageInstaller.STATUS_PENDING_USER_ACTION -> {
|
||||
@Suppress("DEPRECATION")
|
||||
val action = intent.getParcelableExtra<Intent>(Intent.EXTRA_INTENT)
|
||||
confirmation = action; phase = if (action != null) "confirmation" else "error"
|
||||
message = "이 기기에서는 설치 확인이 필요합니다."
|
||||
}
|
||||
PackageInstaller.STATUS_SUCCESS -> { prefs(context).edit().remove("release").remove("session").apply(); phase = "done"; message = "업데이트가 완료됐습니다." }
|
||||
else -> { phase = "error"; message = "설치가 취소되었거나 기기에서 허용되지 않았습니다. 기존 앱과 일정은 유지됩니다." }
|
||||
}
|
||||
}
|
||||
fun confirmationOpened() { confirmation = null; phase = "waiting"; message = "설치 확인을 마친 뒤 앱을 다시 열어 주세요." }
|
||||
}
|
||||
|
||||
/** 외부 앱의 일반 호출을 받지 않는다. 설치 관리자에 전달한 세션 번호가 일치하는 결과만 처리한다. */
|
||||
class UpdateInstallReceiver : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context, intent: Intent) { AppUpdate.result(context, intent) }
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package kr.co.itosm.dutycalendar
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.os.Bundle
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.provider.Settings
|
||||
import android.view.View
|
||||
import android.widget.Button
|
||||
import android.widget.LinearLayout
|
||||
import android.widget.ProgressBar
|
||||
import android.widget.TextView
|
||||
import org.json.JSONObject
|
||||
|
||||
/** 동의한 업데이트의 진행 상태를 보여 준다. 화면이 닫힌 동안 설치 확인창을 강제로 열지 않는다. */
|
||||
class AppUpdateActivity : Activity() {
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
private lateinit var status: TextView
|
||||
private lateinit var progress: ProgressBar
|
||||
private lateinit var action: Button
|
||||
private var autoInstall = true
|
||||
private lateinit var wanted: AppUpdate.Release
|
||||
private val tick = object : Runnable {
|
||||
override fun run() { refresh(); handler.postDelayed(this, 500) }
|
||||
}
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
wanted = runCatching { AppUpdate.parse(JSONObject(intent.getStringExtra("release")!!)) }.getOrNull() ?: AppUpdate.pending(this) ?: run { finish(); return }
|
||||
autoInstall = savedInstanceState?.getBoolean("autoInstall", true) ?: true
|
||||
val form = LinearLayout(this).apply {
|
||||
orientation = LinearLayout.VERTICAL; setPadding(28, 32, 28, 28); setBackgroundColor(0xFFF4F1EA.toInt())
|
||||
setOnApplyWindowInsetsListener { view, insets ->
|
||||
val margin = (20 * resources.displayMetrics.density).toInt()
|
||||
if (android.os.Build.VERSION.SDK_INT >= 30) {
|
||||
val bars = insets.getInsets(android.view.WindowInsets.Type.systemBars() or android.view.WindowInsets.Type.displayCutout())
|
||||
view.setPadding(margin + bars.left, margin + bars.top, margin + bars.right, margin + bars.bottom)
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
view.setPadding(margin + insets.systemWindowInsetLeft, margin + insets.systemWindowInsetTop, margin + insets.systemWindowInsetRight, margin + insets.systemWindowInsetBottom)
|
||||
}
|
||||
insets
|
||||
}
|
||||
}
|
||||
form.addView(TextView(this).apply { text = "당직근무 업데이트"; textSize = 24f; setTextColor(0xFF26364D.toInt()); setPadding(0, 20, 0, 24) })
|
||||
form.addView(TextView(this).apply { text = "새 버전 ${wanted.name}\n다운로드 후 검증을 마치면 적용합니다. 저장한 일정과 설정은 그대로 유지합니다."; textSize = 16f; setPadding(0, 0, 0, 30) })
|
||||
status = TextView(this).apply { textSize = 16f; setPadding(0, 20, 0, 20) }; form.addView(status)
|
||||
progress = ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal).apply { max = 100 }; form.addView(progress, LinearLayout.LayoutParams(-1, 28))
|
||||
action = Button(this).apply { isAllCaps = false; minHeight = 56; visibility = View.GONE }; form.addView(action)
|
||||
form.addView(Button(this).apply { text = "달력으로 돌아가기"; setOnClickListener { finish() } })
|
||||
setContentView(form)
|
||||
if (AppUpdate.installed(this) < wanted.code && (AppUpdate.phase in listOf("idle", "error", "done") || AppUpdate.release != wanted)) AppUpdate.start(this, wanted)
|
||||
}
|
||||
override fun onResume() { super.onResume(); if (::status.isInitialized) handler.post(tick) }
|
||||
override fun onPause() { handler.removeCallbacks(tick); super.onPause() }
|
||||
override fun onSaveInstanceState(outState: Bundle) { outState.putBoolean("autoInstall", autoInstall); super.onSaveInstanceState(outState) }
|
||||
private fun refresh() {
|
||||
if (isFinishing || isDestroyed) return
|
||||
if (AppUpdate.installed(this) >= wanted.code) {
|
||||
status.text = "업데이트가 완료됐습니다. 달력으로 돌아가 주세요."; progress.progress = 100; action.visibility = View.GONE; return
|
||||
}
|
||||
status.text = AppUpdate.message + if (AppUpdate.phase == "downloading") " ${AppUpdate.percent}%" else ""
|
||||
progress.progress = AppUpdate.percent; action.visibility = View.GONE
|
||||
when (AppUpdate.phase) {
|
||||
"ready" -> {
|
||||
if (!packageManager.canRequestPackageInstalls()) {
|
||||
status.text = "내려받기를 마쳤습니다. 처음 한 번 ‘당직근무’의 앱 설치를 허용하면 이후 업데이트를 앱 안에서 적용할 수 있습니다."
|
||||
action.visibility = View.VISIBLE; action.text = "앱 설치 허용 설정"
|
||||
action.setOnClickListener { startActivity(Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:$packageName"))) }
|
||||
} else if (autoInstall) { autoInstall = false; AppUpdate.install(this) }
|
||||
else { action.visibility = View.VISIBLE; action.text = "업데이트 적용"; action.setOnClickListener { AppUpdate.install(this) } }
|
||||
}
|
||||
"confirmation" -> AppUpdate.confirmation?.let { confirmation ->
|
||||
AppUpdate.confirmationOpened()
|
||||
runCatching { startActivity(confirmation) }.onFailure { status.text = "설치 확인창을 열지 못했습니다. 업데이트 확인에서 다시 시도해 주세요." }
|
||||
}
|
||||
"error", "waiting" -> {
|
||||
action.visibility = View.VISIBLE; action.text = "다시 시도"
|
||||
action.setOnClickListener { autoInstall = true; AppUpdate.start(this, wanted) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package kr.co.itosm.dutycalendar
|
||||
|
||||
import android.Manifest
|
||||
import android.app.Activity
|
||||
import android.app.AlertDialog
|
||||
import android.content.ContentUris
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.provider.CalendarContract
|
||||
import android.widget.Toast
|
||||
import org.json.JSONObject
|
||||
import java.time.*
|
||||
import java.util.UUID
|
||||
|
||||
/** 휴대폰 달력은 사용자가 고른 일정만 복사한다. 원본 수정과 삭제 권한은 요구하지 않는다.
|
||||
* 가져오기에는 읽기 권한만 사용한다. 보내기는 시스템 달력의 저장 화면에서 사용자가 마무리한다.
|
||||
* 기기 달력 식별자는 서버에 저장하지 않으며 중복 방지용 식별자만 앱 전용 값과 함께 해시한다.
|
||||
*/
|
||||
class DeviceCalendar(private val activity: Activity, private val changed: () -> Unit) {
|
||||
companion object {
|
||||
const val REQUEST_READ = 7201
|
||||
fun insertIntent(data: JSONObject, occurrence: LocalDate): Intent {
|
||||
val zone=ZoneId.systemDefault();val original=LocalDate.parse(data.getString("date"))
|
||||
val length=java.time.temporal.ChronoUnit.DAYS.between(original,LocalDate.parse(data.getString("endDate")))
|
||||
val allDay=data.getBoolean("allDay")
|
||||
val begin=if(allDay)occurrence.atStartOfDay(ZoneOffset.UTC) else occurrence.atTime(LocalTime.parse(data.getString("startTime"))).atZone(zone)
|
||||
val end=if(allDay)occurrence.plusDays(length+1).atStartOfDay(ZoneOffset.UTC) else occurrence.plusDays(length).atTime(LocalTime.parse(data.getString("endTime"))).atZone(zone)
|
||||
return Intent(Intent.ACTION_INSERT,CalendarContract.Events.CONTENT_URI)
|
||||
.putExtra(CalendarContract.Events.TITLE,data.getString("title"))
|
||||
.putExtra(CalendarContract.Events.DESCRIPTION,data.getString("notes"))
|
||||
.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME,begin.toInstant().toEpochMilli())
|
||||
.putExtra(CalendarContract.EXTRA_EVENT_END_TIME,end.toInstant().toEpochMilli())
|
||||
.putExtra(CalendarContract.EXTRA_EVENT_ALL_DAY,allDay)
|
||||
}
|
||||
fun send(activity: Activity, data: JSONObject, date: LocalDate) {
|
||||
runCatching { activity.startActivity(insertIntent(data,date)) }
|
||||
.onFailure { Toast.makeText(activity,"일정을 받을 달력 앱이 없습니다. 휴대폰에 달력 앱을 설치해 주세요.",Toast.LENGTH_LONG).show() }
|
||||
}
|
||||
fun sendAnniversary(activity: Activity,item:JSONObject) {
|
||||
val data=item.getJSONObject("data");val rule=Anniversaries.rule(data);val today=LocalDate.now()
|
||||
val date=(0L..366L).map{today.plusDays(it)}.firstOrNull{rule.matches(it,if(rule.calendar=="LUNAR")LunarDates.day(activity,it) else null)}
|
||||
if(date==null){Toast.makeText(activity,"제공된 음력 자료 범위에서 다음 날짜를 찾을 수 없습니다.",Toast.LENGTH_LONG).show();return}
|
||||
send(activity,JSONObject().put("title",data.getString("title")).put("notes",Anniversaries.description(data)+"\n"+data.getString("notes"))
|
||||
.put("date",date.toString()).put("endDate",date.toString()).put("allDay",true).put("startTime","09:00").put("endTime","10:00"),date)
|
||||
}
|
||||
}
|
||||
fun open() {
|
||||
AlertDialog.Builder(activity).setTitle("휴대폰 달력 연동")
|
||||
.setMessage("휴대폰 달력에서 선택한 일정만 가져옵니다. 반복 일정은 선택한 날짜의 한 회차를 복사합니다.\n\n앱의 일정을 보내려면 저장된 일정이나 기념일을 열고 ‘휴대폰 달력에 보내기’를 누르세요. 달력 앱에서 최종 저장합니다.\n\n서로의 수정과 삭제를 자동 반영하는 방식은 아닙니다.")
|
||||
.setPositiveButton("일정 가져오기"){_,_->
|
||||
if(activity.checkSelfPermission(Manifest.permission.READ_CALENDAR)==PackageManager.PERMISSION_GRANTED)pickCalendar()
|
||||
else activity.requestPermissions(arrayOf(Manifest.permission.READ_CALENDAR),REQUEST_READ)
|
||||
}.setNegativeButton("닫기",null).show()
|
||||
}
|
||||
fun permissionResult(code:Int,results:IntArray) {
|
||||
if(code!=REQUEST_READ)return
|
||||
if(results.firstOrNull()==PackageManager.PERMISSION_GRANTED)pickCalendar()
|
||||
else Toast.makeText(activity,"달력 읽기를 허용하면 선택한 일정을 가져올 수 있습니다.",Toast.LENGTH_LONG).show()
|
||||
}
|
||||
private fun pickCalendar() {
|
||||
runCatching {
|
||||
val rows=mutableListOf<Pair<Long,String>>()
|
||||
activity.contentResolver.query(CalendarContract.Calendars.CONTENT_URI,arrayOf("_id","calendar_displayName"),"visible=?",arrayOf("1"),null)?.use{cursor->while(cursor.moveToNext())rows.add(cursor.getLong(0) to cursor.getString(1).orEmpty())}
|
||||
if(rows.isEmpty()){Toast.makeText(activity,"휴대폰에 연결된 달력이 없습니다.",Toast.LENGTH_LONG).show();return}
|
||||
AlertDialog.Builder(activity).setTitle("가져올 달력 선택").setItems(rows.map{it.second}.toTypedArray()){_,index->pickEvents(rows[index].first)}.setNegativeButton("취소",null).show()
|
||||
}.onFailure{Toast.makeText(activity,"휴대폰 달력의 읽기 권한과 연결 상태를 확인해 주세요.",Toast.LENGTH_LONG).show()}
|
||||
}
|
||||
private fun pickEvents(calendar:Long) {
|
||||
val today=LocalDate.now();val zone=ZoneId.systemDefault()
|
||||
val uri=CalendarContract.Instances.CONTENT_URI.buildUpon().also{
|
||||
ContentUris.appendId(it,today.minusDays(30).atStartOfDay(zone).toInstant().toEpochMilli());ContentUris.appendId(it,today.plusDays(366).atStartOfDay(zone).toInstant().toEpochMilli())
|
||||
}.build()
|
||||
val candidates=mutableListOf<Pair<String,JSONObject>>()
|
||||
runCatching {
|
||||
val prefs=activity.getSharedPreferences("device_calendar",0)
|
||||
val salt=prefs.getString("id",null)?:UUID.randomUUID().toString().also{prefs.edit().putString("id",it).commit()}
|
||||
activity.contentResolver.query(uri,arrayOf("event_id","title","begin","end","allDay","description"),"calendar_id=?",arrayOf(calendar.toString()),"begin ASC")?.use{cursor->
|
||||
while(cursor.moveToNext()&&candidates.size<100){
|
||||
val allDay=cursor.getInt(4)==1;val eventZone=if(allDay)ZoneOffset.UTC else zone
|
||||
val begin=Instant.ofEpochMilli(cursor.getLong(2)).atZone(eventZone);val finish=Instant.ofEpochMilli(cursor.getLong(3)).atZone(eventZone)
|
||||
if(!finish.isAfter(begin))continue
|
||||
val end=if(allDay)finish.toLocalDate().minusDays(1) else finish.toLocalDate()
|
||||
if(begin.year !in 2000..2099||end.year !in 2000..2099||java.time.temporal.ChronoUnit.DAYS.between(begin.toLocalDate(),end)>366)continue
|
||||
val id=UUID.nameUUIDFromBytes("$salt:$calendar:${cursor.getLong(0)}:${cursor.getLong(2)}".toByteArray()).toString()
|
||||
val value=JSONObject().put("title",cursor.getString(1).orEmpty().ifBlank{"제목 없는 일정"}.take(120)).put("notes",cursor.getString(5).orEmpty().take(2000)).put("category","GENERAL")
|
||||
.put("date",begin.toLocalDate().toString()).put("endDate",end.toString()).put("allDay",allDay)
|
||||
.put("startTime",begin.toLocalTime().withSecond(0).withNano(0).toString()).put("endTime",finish.toLocalTime().withSecond(0).withNano(0).toString())
|
||||
.put("repeat","NONE").put("repeatUntil","").put("reminderMinutes",-1)
|
||||
if(runCatching{PlannerStore.validateEvent(value)}.isSuccess)candidates.add(id to value)
|
||||
}
|
||||
}
|
||||
}.onFailure{Toast.makeText(activity,"휴대폰 일정을 읽지 못했습니다.",Toast.LENGTH_LONG).show();return}
|
||||
if(candidates.isEmpty()){Toast.makeText(activity,"지난 30일부터 앞으로 1년 사이의 일정이 없습니다.",Toast.LENGTH_LONG).show();return}
|
||||
val selected=BooleanArray(candidates.size)
|
||||
AlertDialog.Builder(activity).setTitle("가져올 일정 · 최대 100개")
|
||||
.setMultiChoiceItems(candidates.map{it.second.getString("date")+" · "+it.second.getString("title")}.toTypedArray(),selected){_,index,value->selected[index]=value}
|
||||
.setNegativeButton("취소",null).setPositiveButton("선택한 일정 가져오기"){_,_->
|
||||
val chosen=candidates.filterIndexed{index,_->selected[index]};if(chosen.isEmpty())return@setPositiveButton
|
||||
AlertDialog.Builder(activity).setTitle("${chosen.size}개 일정을 가져올까요?")
|
||||
.setMessage(if(SyncClient.connected(activity))"선택한 일정과 메모를 내 회원 계정의 서버에도 저장합니다. 이미 가져온 일정은 건너뜁니다." else "선택한 일정과 메모를 이 기기에 저장합니다. 나중에 웹 연동을 켜면 내 서버 계정에도 저장합니다. 이미 가져온 일정은 건너뜁니다.")
|
||||
.setNegativeButton("취소",null).setPositiveButton("가져오기"){_,_->
|
||||
var count=0;val existing=PlannerStore.items(activity).map{it.getString("id")}.toSet()
|
||||
val result=runCatching{for((id,data) in chosen)if(id !in existing){PlannerStore.put(activity,id,"event",data);count++}}
|
||||
SyncClient.sync(activity);changed()
|
||||
Toast.makeText(activity,"${count}개 일정을 저장했습니다."+if(result.isFailure)" 나머지는 저장 공간을 확인한 뒤 다시 가져오세요." else "",Toast.LENGTH_LONG).show()
|
||||
}.show()
|
||||
}.show()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
package kr.co.itosm.dutycalendar
|
||||
|
||||
import android.app.PendingIntent
|
||||
import android.appwidget.AppWidgetManager
|
||||
import android.appwidget.AppWidgetProvider
|
||||
import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.os.Bundle
|
||||
import android.text.SpannableString
|
||||
import android.text.Spanned
|
||||
import android.text.style.ForegroundColorSpan
|
||||
import android.text.style.StyleSpan
|
||||
import android.graphics.Typeface
|
||||
import android.text.style.RelativeSizeSpan
|
||||
import android.widget.RemoteViews
|
||||
import java.time.LocalDate
|
||||
import java.time.YearMonth
|
||||
|
||||
/**
|
||||
* 홈 화면 앱이 표시할 달력을 RemoteViews로 전달한다. 앱 화면을 계속 켜 둘 필요는 없다.
|
||||
* 위젯마다 보고 있는 달을 따로 저장하므로 여러 개를 배치해도 월 이동이 서로 영향을 주지 않는다.
|
||||
* 월을 고르지 않은 위젯은 현재 달을 따라간다. 직접 이동한 위젯은 오늘 버튼을 누를 때까지 선택을 유지한다.
|
||||
* 날짜 변경과 부팅 알림 및 주기 갱신으로 오늘 표시를 갱신한다. 실제 전달 시점은 운영체제의 영향을 받는다.
|
||||
*/
|
||||
class DutyWidget : AppWidgetProvider() {
|
||||
override fun onUpdate(context: Context, manager: AppWidgetManager, ids: IntArray) {
|
||||
Holidays.schedule(context)
|
||||
SyncClient.schedule(context)
|
||||
ids.forEach { update(context, manager, it) }
|
||||
}
|
||||
override fun onAppWidgetOptionsChanged(context: Context, manager: AppWidgetManager, id: Int, options: Bundle) { update(context, manager, id) }
|
||||
override fun onDeleted(context: Context, ids: IntArray) {
|
||||
val editor = context.getSharedPreferences("widget", Context.MODE_PRIVATE).edit()
|
||||
ids.forEach { editor.remove("month_$it") }
|
||||
editor.apply()
|
||||
context.getSharedPreferences("widget_style",0).edit().apply { ids.forEach { remove("style_$it") } }.apply()
|
||||
}
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
super.onReceive(context, intent)
|
||||
val manager = AppWidgetManager.getInstance(context)
|
||||
val action = intent.action ?: return
|
||||
if (action in listOf(PREVIOUS, NEXT, TODAY)) {
|
||||
val id = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1)
|
||||
// 삭제된 위젯이나 이 앱에 속하지 않은 번호로 들어온 요청은 처리하지 않는다.
|
||||
if (id !in manager.getAppWidgetIds(ComponentName(context, DutyWidget::class.java))) return
|
||||
val prefs = context.getSharedPreferences("widget", Context.MODE_PRIVATE)
|
||||
val editor = prefs.edit()
|
||||
if (action == TODAY) editor.remove("month_$id")
|
||||
else editor.putString("month_$id", selectedMonth(context, id).plusMonths(if (action == NEXT) 1 else -1).toString())
|
||||
editor.apply()
|
||||
update(context, manager, id)
|
||||
} else if (action in listOf(Intent.ACTION_DATE_CHANGED, Intent.ACTION_TIME_CHANGED, Intent.ACTION_TIMEZONE_CHANGED, Intent.ACTION_BOOT_COMPLETED)) {
|
||||
Holidays.schedule(context)
|
||||
SyncClient.schedule(context)
|
||||
updateAll(context)
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val PREVIOUS = "kr.co.itosm.dutycalendar.PREVIOUS"
|
||||
private const val NEXT = "kr.co.itosm.dutycalendar.NEXT"
|
||||
private const val TODAY = "kr.co.itosm.dutycalendar.TODAY"
|
||||
// 날짜 칸의 리소스 참조를 명시해 코드와 42칸 레이아웃의 순서를 맞춘다.
|
||||
// 문자열로 리소스를 찾지 않으므로 이름 변경이나 리소스 축소 때도 참조 관계를 추적할 수 있다.
|
||||
private val DAY_IDS = intArrayOf(
|
||||
R.id.day_0, R.id.day_1, R.id.day_2, R.id.day_3, R.id.day_4, R.id.day_5, R.id.day_6,
|
||||
R.id.day_7, R.id.day_8, R.id.day_9, R.id.day_10, R.id.day_11, R.id.day_12, R.id.day_13,
|
||||
R.id.day_14, R.id.day_15, R.id.day_16, R.id.day_17, R.id.day_18, R.id.day_19, R.id.day_20,
|
||||
R.id.day_21, R.id.day_22, R.id.day_23, R.id.day_24, R.id.day_25, R.id.day_26, R.id.day_27,
|
||||
R.id.day_28, R.id.day_29, R.id.day_30, R.id.day_31, R.id.day_32, R.id.day_33, R.id.day_34,
|
||||
R.id.day_35, R.id.day_36, R.id.day_37, R.id.day_38, R.id.day_39, R.id.day_40, R.id.day_41
|
||||
)
|
||||
// 저장된 월을 읽지 못해도 위젯을 비워 두지 않는다. 현재 달로 복구해 정상적인 표시를 유지한다.
|
||||
private fun selectedMonth(context: Context, id: Int): YearMonth = runCatching {
|
||||
YearMonth.parse(context.getSharedPreferences("widget", Context.MODE_PRIVATE).getString("month_$id", YearMonth.now().toString()))
|
||||
}.getOrDefault(YearMonth.now())
|
||||
|
||||
fun updateAll(context: Context) {
|
||||
val manager = AppWidgetManager.getInstance(context)
|
||||
manager.getAppWidgetIds(ComponentName(context, DutyWidget::class.java)).forEach { update(context, manager, it) }
|
||||
}
|
||||
private fun update(context: Context, manager: AppWidgetManager, id: Int) {
|
||||
manager.updateAppWidget(id, buildViews(context,id,manager.getAppWidgetOptions(id)))
|
||||
}
|
||||
internal fun buildViews(context:Context,id:Int,options:Bundle):RemoteViews {
|
||||
val style=WidgetStyle.load(context,id)
|
||||
val portrait=context.resources.configuration.orientation!=android.content.res.Configuration.ORIENTATION_LANDSCAPE
|
||||
val height=options.getInt(if(portrait)AppWidgetManager.OPTION_APPWIDGET_MAX_HEIGHT else AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT,420).coerceIn(250,1200)
|
||||
val compact=style.compact(height)
|
||||
val density=context.resources.displayMetrics.density
|
||||
val month = selectedMonth(context, id)
|
||||
val schedule = ScheduleStore.load(context)
|
||||
val people = if(style.people&&!compact)People.all(context) else emptyList()
|
||||
val today = LocalDate.now()
|
||||
val configured = ScheduleStore.isConfigured(context)
|
||||
val view = RemoteViews(context.packageName, R.layout.duty_widget)
|
||||
// 배경만 투명하게 바꾸고 글자는 독립된 색으로 남긴다. 배경 교체 시 사라지는 안쪽 여백도 명시한다.
|
||||
view.setInt(R.id.widget_root,"setBackgroundColor",style.background)
|
||||
view.setViewPadding(R.id.widget_root,(12*density).toInt(),(10*density).toInt(),(12*density).toInt(),(10*density).toInt())
|
||||
for(control in listOf(R.id.widget_title,R.id.widget_today,R.id.widget_customize,R.id.widget_previous,R.id.widget_next))view.setTextColor(control,style.ink)
|
||||
for(control in listOf(R.id.widget_subtitle,R.id.widget_footer,R.id.widget_mon,R.id.widget_tue,R.id.widget_wed,R.id.widget_thu,R.id.widget_fri))view.setTextColor(control,style.muted)
|
||||
view.setTextColor(R.id.widget_sun,style.color(0xFFBD5163.toInt()))
|
||||
view.setTextColor(R.id.widget_saturday, style.color(schedule.saturdayColor))
|
||||
view.setTextViewTextSize(R.id.widget_title,android.util.TypedValue.COMPLEX_UNIT_SP,18f*style.scale/100)
|
||||
val customize=Intent(context,MainActivity::class.java).setData(android.net.Uri.parse("dutycalendar://widget/$id/style")).putExtra("widgetStyleId",id)
|
||||
view.setOnClickPendingIntent(R.id.widget_customize,PendingIntent.getActivity(context,id,customize,PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE))
|
||||
view.setTextViewText(R.id.widget_title, "${month.year}년 ${month.monthValue}월")
|
||||
view.setTextViewText(R.id.widget_subtitle, if (configured) "오늘 ${schedule.shiftOn(today).title} · ${schedule.pattern.size}일 반복" else "앱에서 근무 시작 날짜를 설정해 주세요")
|
||||
view.setTextViewText(R.id.widget_footer, if (month.year in Holidays.years(context)) "제작자 블리어 (이창현)" else "${month.year}년 공휴일 자료 확인 필요")
|
||||
val open = PendingIntent.getActivity(context, 0, Intent(context, MainActivity::class.java), PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
|
||||
view.setOnClickPendingIntent(R.id.widget_root, open)
|
||||
// 같은 동작도 위젯 번호별로 다른 PendingIntent를 사용한다. 다른 위젯의 월을 바꾸지 않기 위해서다.
|
||||
// 명시적 수신 대상과 변경 불가 플래그를 사용해 홈 화면 앱이 전달 내용을 바꾸지 못하게 한다.
|
||||
listOf(R.id.widget_previous to PREVIOUS, R.id.widget_next to NEXT, R.id.widget_today to TODAY).forEach { (control, action) ->
|
||||
val intent = Intent(context, DutyWidget::class.java).setAction(action).putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, id)
|
||||
view.setOnClickPendingIntent(control, PendingIntent.getBroadcast(context, id, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE))
|
||||
}
|
||||
calendarDays(month).forEachIndexed { index, date ->
|
||||
val shift = schedule.shiftOn(date)
|
||||
val holiday = Holidays.name(context, date)
|
||||
val events = PlannerStore.eventsOn(context, date)
|
||||
val personalDays = Anniversaries.on(context, date)
|
||||
val number = date.dayOfMonth.toString() + if (style.eventMark && (events.isNotEmpty() || personalDays.isNotEmpty())) "+" else ""
|
||||
val holidayShort = holiday?.takeIf { style.holidays&&!compact }?.let { if (it.contains("대체공휴일")) "대체휴일" else it.replace(" 전날", "").replace(" 다음 날", "").replace("기독탄신일", "성탄절").replace("1월 1일", "신정") }
|
||||
val lunar = if (schedule.showLunar&&style.lunar&&!compact) LunarDates.label(context, date) else null
|
||||
val heading = number + (lunar?.let { "\n$it" } ?: "")
|
||||
val shiftStart = heading.length + 1
|
||||
val baseText = "$heading\n${shift.shortTitle}" + (holidayShort?.let { "\n$it" } ?: "")
|
||||
val colleagues = People.onDuty(people, date)
|
||||
// 작은 위젯에는 두 줄까지만 표시한다. 사람이 많아도 날짜의 높이와 정렬을 유지하고 전체 이름은 눌러서 확인한다.
|
||||
val names = if (colleagues.size > 2) listOf(colleagues.first().name.take(3), "외${colleagues.size - 1}명") else colleagues.map { it.name.take(3) }
|
||||
val cellText = baseText + names.joinToString("", transform = { "\n$it" }) + if (style.anniversaries&&!compact&&personalDays.isNotEmpty()) "\n" + personalDays.first().getJSONObject("data").getString("title").take(5) else ""
|
||||
// 하나의 날짜 칸 안에서 날짜와 근무 및 공휴일 색상을 따로 지정한다.
|
||||
// 전체 공휴일 이름은 접근성 설명에 남기고 화면에는 폭에 맞는 짧은 표기를 사용한다.
|
||||
val styled = SpannableString(cellText)
|
||||
val dateColor = style.color(schedule.dateColor(date, holiday != null))
|
||||
styled.setSpan(StyleSpan(Typeface.BOLD), 0, number.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
|
||||
styled.setSpan(StyleSpan(Typeface.BOLD), shiftStart, shiftStart + shift.shortTitle.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
|
||||
styled.setSpan(ForegroundColorSpan(dateColor), 0, number.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
|
||||
styled.setSpan(ForegroundColorSpan(style.color(schedule.shiftColor(date))), shiftStart, shiftStart + shift.shortTitle.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
|
||||
styled.setSpan(RelativeSizeSpan(0.85f), number.length + 1, cellText.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
|
||||
if (holidayShort != null) styled.setSpan(ForegroundColorSpan(style.color(0xFFBD5163.toInt())), shiftStart + 1 + shift.shortTitle.length, baseText.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
|
||||
if (lunar != null) {
|
||||
styled.setSpan(RelativeSizeSpan(0.75f), number.length + 1, heading.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
|
||||
styled.setSpan(ForegroundColorSpan(style.muted), number.length + 1, heading.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
|
||||
}
|
||||
var nameStart = baseText.length + 1
|
||||
names.forEachIndexed { i, name ->
|
||||
styled.setSpan(ForegroundColorSpan(if (colleagues.size > 2 && i == 1) style.muted else style.color(colleagues[i].color)), nameStart, nameStart + name.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
|
||||
nameStart += name.length + 1
|
||||
}
|
||||
if (YearMonth.from(date) != month) {
|
||||
styled.setSpan(ForegroundColorSpan(0xFF9AA4B3.toInt()), 0, cellText.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
|
||||
}
|
||||
val cellId = DAY_IDS[index]
|
||||
view.setTextViewText(cellId, styled)
|
||||
view.setInt(cellId, "setMaxLines", if(compact)2 else 7)
|
||||
// 여섯 주를 같은 높이로 유지한다. 작은 위젯의 자동 배치는 글줄을 줄이고 사용자 글자 배율을 적용한다.
|
||||
val baseSize=((height-120)/6f/(if(compact)2.6f else 5.4f)).coerceIn(11f,17f)
|
||||
view.setTextViewTextSize(cellId,android.util.TypedValue.COMPLEX_UNIT_SP,baseSize*style.scale/100)
|
||||
view.setInt(cellId, "setGravity", android.view.Gravity.TOP or android.view.Gravity.CENTER_HORIZONTAL)
|
||||
view.setViewPadding(cellId, 0, ((if(compact)2 else 5)*density).toInt(), 0, 0)
|
||||
view.setTextColor(cellId, if (YearMonth.from(date) == month) style.ink else 0xFF9AA4B3.toInt())
|
||||
view.setInt(cellId, "setBackgroundColor", if (date == today && style.today) (if(style.dark)0x554A6D96 else 0x44A7B5CB) else android.graphics.Color.TRANSPARENT)
|
||||
view.setContentDescription(cellId, "${date.monthValue}월 ${date.dayOfMonth}일 ${shift.title} ${lunar.orEmpty()} ${holiday.orEmpty()} 일정 ${events.size}개. 기념일: ${personalDays.joinToString { it.getJSONObject("data").getString("title") }}. 함께 당직: ${colleagues.joinToString { it.name }}")
|
||||
val dayIntent = Intent(context, MainActivity::class.java).setData(android.net.Uri.parse("dutycalendar://date/$date")).putExtra("selectedDate", date.toString())
|
||||
view.setOnClickPendingIntent(cellId, PendingIntent.getActivity(context, id * 1000 + index + 1, dayIntent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE))
|
||||
}
|
||||
return view
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package kr.co.itosm.dutycalendar
|
||||
|
||||
import java.time.LocalDate
|
||||
import java.time.temporal.ChronoUnit
|
||||
|
||||
/** 반복 시작일은 항상 최초 날짜에서 계산한다. 1월 31일 다음이 2월 말일이어도 3월은 다시 31일이다.
|
||||
* 반복 종료일은 마지막 시작일의 한계다. 그날 시작한 여러 날 일정은 원래 기간까지 표시한다.
|
||||
*/
|
||||
data class EventRepeat(val start: LocalDate, val end: LocalDate, val frequency: String = "NONE", val until: LocalDate? = null) {
|
||||
init {
|
||||
require(frequency in listOf("NONE","DAILY","WEEKLY","MONTHLY","YEARLY")) { "반복 종류를 확인해 주세요." }
|
||||
require(end >= start && ChronoUnit.DAYS.between(start,end) <= 366 && (until == null || (until >= start && until.year in 2000..2099))) { "일정 기간과 반복 종료일을 확인해 주세요." }
|
||||
}
|
||||
fun occurrenceOn(date: LocalDate): LocalDate? {
|
||||
if(date < start)return null
|
||||
val limit=if(until!=null&&until<date)until else date
|
||||
if(limit<start)return null
|
||||
val candidate=when(frequency) {
|
||||
"DAILY" -> limit
|
||||
"WEEKLY" -> start.plusWeeks(ChronoUnit.DAYS.between(start,limit)/7)
|
||||
"MONTHLY" -> {
|
||||
var gap=ChronoUnit.MONTHS.between(start.withDayOfMonth(1),limit.withDayOfMonth(1));if(start.plusMonths(gap)>limit)gap--
|
||||
start.plusMonths(gap)
|
||||
}
|
||||
"YEARLY" -> {var gap=(limit.year-start.year).toLong();if(start.plusYears(gap)>limit)gap--;start.plusYears(gap)}
|
||||
else -> start
|
||||
}
|
||||
return candidate.takeIf{it>=start&&date<=it.plusDays(ChronoUnit.DAYS.between(start,end))}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package kr.co.itosm.dutycalendar
|
||||
|
||||
import android.app.job.JobParameters
|
||||
import android.app.job.JobService
|
||||
|
||||
/**
|
||||
* 앱 화면이 닫혀 있을 때 공휴일 갱신을 연결하는 운영체제 예약 작업이다.
|
||||
* 다운로드는 Holidays의 작업 스레드에서 수행한다. 완료되면 결과를 예약 관리자에 돌려준다.
|
||||
* 실패하거나 운영체제가 작업을 중단하면 재시도를 요청한다. 실제 재실행 시점은 절전 정책을 따른다.
|
||||
*/
|
||||
class HolidaySyncService : JobService() {
|
||||
override fun onStartJob(params: JobParameters): Boolean {
|
||||
Holidays.refresh(applicationContext) { success -> jobFinished(params, !success) }
|
||||
return true
|
||||
}
|
||||
// 이미 시작한 통신을 강제로 끊지는 않는다. 통신 제한 시간 안에 끝나며 중복 쓰기는 Holidays가 막는다.
|
||||
override fun onStopJob(params: JobParameters): Boolean = true
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
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.util.AtomicFile
|
||||
import org.json.JSONObject
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.io.File
|
||||
import java.net.URL
|
||||
import java.time.LocalDate
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
import javax.net.ssl.HttpsURLConnection
|
||||
|
||||
/**
|
||||
* 공휴일 자료는 메모리와 기기 내부 파일에 보관한다. 설치 직후에는 앱에 포함된 자료를 사용한다.
|
||||
* 공개 자료를 내려받아 구조와 날짜를 검증한 뒤에만 교체한다. 통신 오류로 기존 자료를 지우지 않는다.
|
||||
* 자료의 갱신과 근무 주기의 계산을 분리해 인터넷 연결이 없어도 근무표를 볼 수 있게 한다.
|
||||
*/
|
||||
object Holidays {
|
||||
const val SOURCE = "https://duty.itosm.co.kr/calendar/api/holidays"
|
||||
private const val MONTH_MS = RefreshPolicy.MONTH_MS
|
||||
@Volatile private var cached: Map<LocalDate, List<String>>? = null
|
||||
// 앱의 수동 갱신과 예약 작업이 겹쳐 같은 파일을 동시에 쓰는 것을 막는다.
|
||||
private val syncing = AtomicBoolean(false)
|
||||
private fun prefs(context: Context) = context.getSharedPreferences("holidays", Context.MODE_PRIVATE)
|
||||
private fun file(context: Context) = AtomicFile(File(context.filesDir, "holidays.json"))
|
||||
|
||||
/**
|
||||
* 원본 형식은 연도 아래에 날짜별 공휴일 이름 배열이 들어 있는 구조다.
|
||||
* 하나의 날짜에 여러 공휴일이 겹칠 수 있으므로 이름을 하나로 덮어쓰지 않는다.
|
||||
* 연도와 날짜가 맞지 않거나 이름이 비어 있으면 전체 응답을 거부한다.
|
||||
* 제공 자료의 형식이 바뀐 경우에도 잘못 해석한 내용을 저장하는 대신 이전 자료를 유지한다.
|
||||
*/
|
||||
internal fun parse(text: String): Map<LocalDate, List<String>> {
|
||||
val root = JSONObject(text)
|
||||
val result = linkedMapOf<LocalDate, List<String>>()
|
||||
val years = root.keys()
|
||||
while (years.hasNext()) {
|
||||
val year = years.next()
|
||||
require(year.matches(Regex("20[0-9]{2}")))
|
||||
val dates = root.getJSONObject(year)
|
||||
val keys = dates.keys()
|
||||
while (keys.hasNext()) {
|
||||
val key = keys.next()
|
||||
val date = LocalDate.parse(key)
|
||||
require(date.year.toString() == year)
|
||||
val values = dates.getJSONArray(key)
|
||||
require(values.length() in 1..8)
|
||||
result[date] = List(values.length()) { index ->
|
||||
values.getString(index).trim().also { require(it.isNotEmpty() && it.length <= 100) }
|
||||
}
|
||||
}
|
||||
}
|
||||
// 오류 페이지나 불완전한 응답 때문에 저장된 공휴일을 지우지 않도록 최소 범위를 확인한다.
|
||||
require(result.size >= 10)
|
||||
return result
|
||||
}
|
||||
|
||||
// 여러 화면이 동시에 처음 읽더라도 파일을 중복 해석하지 않도록 초기 적재를 동기화한다.
|
||||
// 저장 파일을 읽을 수 없으면 기본 자료로 대체한다. 기본 자료 자체는 배포 전에 검증해야 한다.
|
||||
@Synchronized fun all(context: Context): Map<LocalDate, List<String>> {
|
||||
cached?.let { return it }
|
||||
val data = runCatching { parse(file(context).openRead().bufferedReader(Charsets.UTF_8).use { it.readText() }) }
|
||||
.getOrElse { parse(context.assets.open("holidays.json").bufferedReader(Charsets.UTF_8).use { it.readText() }) }
|
||||
cached = data
|
||||
return data
|
||||
}
|
||||
fun name(context: Context, date: LocalDate): String? = all(context)[date]?.joinToString(" · ")
|
||||
fun years(context: Context) = all(context).keys.map { it.year }.toSet()
|
||||
fun updatedAt(context: Context) = prefs(context).getLong("updatedAt", 0L)
|
||||
fun usesSaved(context: Context) = prefs(context).getBoolean("usesSaved", true)
|
||||
fun revision(context: Context) = prefs(context).getString("revision", "").orEmpty()
|
||||
|
||||
/**
|
||||
* 일반 실행에서는 마지막 성공 시각으로부터 한 달이 지나야 다시 조회한다.
|
||||
* 수동 갱신과 예약 작업은 force로 주기를 건너뛸 수 있다. 이미 조회 중이면 중복 요청은 실패로 알린다.
|
||||
* 완료 콜백은 호출 경로에 따라 현재 스레드나 작업 스레드에서 실행된다.
|
||||
* 화면을 갱신하는 호출자는 반드시 메인 스레드로 전환하고 화면이 종료됐는지도 확인해야 한다.
|
||||
*/
|
||||
fun refresh(context: Context, force: Boolean = false, changedOnly: Boolean = false, complete: (Boolean) -> Unit = {}) {
|
||||
val app = context.applicationContext
|
||||
if (!force && System.currentTimeMillis() - prefs(app).getLong("checkedAt", 0L) < MONTH_MS) { complete(true); return }
|
||||
if (!syncing.compareAndSet(false, true)) { complete(false); return }
|
||||
Thread({
|
||||
var success = false
|
||||
var connection: HttpsURLConnection? = null
|
||||
try {
|
||||
connection = URL(SOURCE + if (force && !changedOnly) "?refresh=true" else "").openConnection() as HttpsURLConnection
|
||||
connection.connectTimeout = 8_000
|
||||
connection.readTimeout = 8_000
|
||||
connection.setRequestProperty("Accept", "application/json")
|
||||
check(connection.responseCode == 200)
|
||||
val bytes = ByteArrayOutputStream()
|
||||
connection.inputStream.use { input ->
|
||||
val buffer = ByteArray(8192)
|
||||
while (true) {
|
||||
val count = input.read(buffer)
|
||||
if (count < 0) break
|
||||
// 비정상적으로 큰 응답이 메모리를 계속 점유하지 않도록 1MiB에서 제한한다.
|
||||
check(bytes.size() + count <= 1_048_576)
|
||||
bytes.write(buffer, 0, count)
|
||||
}
|
||||
}
|
||||
val data = parse(bytes.toString("UTF-8"))
|
||||
// 올해 자료가 빠진 응답은 갱신 성공으로 보지 않는다. 미래 연도는 제공되는 범위만 표시한다.
|
||||
check(data.keys.count { it.year == LocalDate.now().year } >= 10)
|
||||
val target = file(app)
|
||||
// 쓰는 도중 종료되거나 저장 공간이 부족해도 이전 파일을 되살릴 수 있도록 AtomicFile을 쓴다.
|
||||
val stream = target.startWrite()
|
||||
try { stream.write(bytes.toByteArray()); target.finishWrite(stream) }
|
||||
catch (error: Exception) { target.failWrite(stream); throw error }
|
||||
cached = data
|
||||
prefs(app).edit().putLong("checkedAt", System.currentTimeMillis())
|
||||
.putLong("updatedAt", (connection.getHeaderField("X-Holiday-Checked")?.toLongOrNull() ?: 0L) * 1000)
|
||||
.putBoolean("usesSaved", connection.getHeaderField("X-Holiday-Saved") == "1")
|
||||
.putString("revision", connection.getHeaderField("X-Holiday-Revision").orEmpty()).apply()
|
||||
DutyWidget.updateAll(app)
|
||||
success = true
|
||||
} catch (_: Exception) {
|
||||
// 연결 실패 때는 직전에 검증한 자료를 계속 사용한다. 근무표 자체는 네트워크에 의존하지 않는다.
|
||||
} finally {
|
||||
connection?.disconnect()
|
||||
syncing.set(false)
|
||||
complete(success)
|
||||
}
|
||||
}, "holiday-sync").start()
|
||||
}
|
||||
|
||||
/**
|
||||
* 네트워크가 연결됐을 때 30일 주기로 갱신을 요청한다. 정확한 실행 시각은 운영체제가 결정한다.
|
||||
* 같은 작업을 매번 새로 등록하면 예정 시각이 밀릴 수 있어 등록 여부를 먼저 확인한다.
|
||||
* 재부팅 후에도 예약을 유지하려면 매니페스트의 부팅 수신 권한이 필요하다.
|
||||
*/
|
||||
fun schedule(context: Context) {
|
||||
val scheduler = context.getSystemService(JobScheduler::class.java)
|
||||
val job = scheduler.getPendingJob(2101)
|
||||
if (job?.intervalMillis != MONTH_MS || job.flexMillis != RefreshPolicy.FLEX_MS) {
|
||||
scheduler.cancel(2101)
|
||||
scheduler.schedule(JobInfo.Builder(2101, ComponentName(context, HolidaySyncService::class.java))
|
||||
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
|
||||
.setPeriodic(MONTH_MS, RefreshPolicy.FLEX_MS).setPersisted(true).build())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package kr.co.itosm.dutycalendar
|
||||
|
||||
import android.content.Context
|
||||
import org.json.JSONObject
|
||||
import java.time.LocalDate
|
||||
|
||||
/**
|
||||
* 한국 음력의 월 시작일을 설치 파일에 함께 넣는다. 중국 음력으로 대신 계산하지 않는다.
|
||||
* 음력 월은 29일 또는 30일이므로 시작일을 찾은 뒤 날짜 차이만 더한다. 윤달은 별도로 표기한다.
|
||||
* 검증된 변환 범위를 벗어나면 표시하지 않는다. 알 수 없는 음력 날짜를 추정해서 보여 주지 않는다.
|
||||
*/
|
||||
object LunarDates {
|
||||
@Volatile private var table: LunarTable? = null
|
||||
@Synchronized private fun load(context: Context): LunarTable {
|
||||
table?.let { return it }
|
||||
val json = JSONObject(context.assets.open("lunar-months.json").bufferedReader(Charsets.UTF_8).use { it.readText() })
|
||||
val rows = json.getJSONArray("months")
|
||||
var year = 1899
|
||||
return LunarTable(List(rows.length()) { index -> rows.getJSONArray(index).let {
|
||||
if (it.getInt(1) == 1 && it.getInt(2) == 0) year = LocalDate.ofEpochDay(it.getLong(0)).year
|
||||
LunarMonth(it.getLong(0), it.getInt(1), it.getInt(2) == 1, year)
|
||||
} }).also { table = it }
|
||||
}
|
||||
fun day(context: Context, date: LocalDate) = load(context).day(date)
|
||||
fun label(context: Context, date: LocalDate): String? {
|
||||
val day = day(context, date) ?: return null
|
||||
return "${if (day.leap) "윤" else "음"}${day.month}.${day.day}"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,431 @@
|
||||
package kr.co.itosm.dutycalendar
|
||||
|
||||
import android.app.Activity
|
||||
import android.app.AlertDialog
|
||||
import android.app.DatePickerDialog
|
||||
import android.appwidget.AppWidgetManager
|
||||
import android.content.ComponentName
|
||||
import android.graphics.Typeface
|
||||
import android.graphics.drawable.GradientDrawable
|
||||
import android.os.Bundle
|
||||
import android.view.Gravity
|
||||
import android.view.View
|
||||
import android.widget.*
|
||||
import java.time.LocalDate
|
||||
import java.time.YearMonth
|
||||
import java.time.format.DateTimeFormatter
|
||||
import java.util.Locale
|
||||
|
||||
/**
|
||||
* 오늘의 근무와 월간 달력 및 반복 설정을 한 화면에서 제공한다.
|
||||
* 저장된 근무표를 읽어 화면을 다시 그리며 월 이동만으로 저장된 기준일을 바꾸지 않는다.
|
||||
* 위젯과 계산식을 따로 만들지 않고 Schedule과 Holidays를 공유해 표시 결과를 맞춘다.
|
||||
*/
|
||||
class MainActivity : Activity() {
|
||||
private var month = YearMonth.now()
|
||||
private var selectedDate = LocalDate.now()
|
||||
private val planner by lazy { PlannerDialogs(this) { render() } }
|
||||
private val peopleEditor by lazy { PeopleDialogs(this) { render() } }
|
||||
private val anniversaries by lazy { AnniversaryDialogs(this) { render() } }
|
||||
private val deviceCalendar by lazy { DeviceCalendar(this) { render() } }
|
||||
private lateinit var content: LinearLayout
|
||||
private var scrollOffset = 0
|
||||
private var restoringScroll = false
|
||||
private var renderGeneration = 0
|
||||
private val ink = 0xFF26364D.toInt()
|
||||
private val muted = 0xFF626976.toInt()
|
||||
private val accent = 0xFF26364D.toInt()
|
||||
private fun dp(value: Int) = (value * resources.displayMetrics.density).toInt()
|
||||
private fun background(color: Int, radius: Int = 5, border: Int? = null) = GradientDrawable().apply {
|
||||
setColor(color); cornerRadius = dp(radius).toFloat()
|
||||
border?.let { setStroke(dp(1), it) }
|
||||
}
|
||||
private fun label(value: String, size: Float = 15f, color: Int = ink, bold: Boolean = false) = TextView(this).apply {
|
||||
text = value; textSize = size; setTextColor(color)
|
||||
if (bold) setTypeface(typeface, Typeface.BOLD)
|
||||
}
|
||||
private fun column() = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL }
|
||||
private fun row() = LinearLayout(this).apply { orientation = LinearLayout.HORIZONTAL; gravity = Gravity.CENTER_VERTICAL }
|
||||
private fun button(title: String, filled: Boolean = false, action: () -> Unit) = Button(this).apply {
|
||||
text = title; isAllCaps = false; textSize = 14f
|
||||
minHeight = dp(48); minimumHeight = dp(48)
|
||||
setTextColor(if (filled) 0xFFFFFFFF.toInt() else accent)
|
||||
background = background(if (filled) accent else 0xFFEBEDF2.toInt(), 5)
|
||||
setPadding(dp(12), dp(8), dp(12), dp(8))
|
||||
setOnClickListener { action() }
|
||||
}
|
||||
private fun space(parent: LinearLayout, height: Int) { parent.addView(View(this), LinearLayout.LayoutParams(1, dp(height))) }
|
||||
private fun card(parent: LinearLayout, color: Int = 0xFFFFFFFF.toInt()): LinearLayout {
|
||||
return column().apply {
|
||||
background = background(color, 5, 0xFFDEDED8.toInt())
|
||||
setPadding(dp(16), dp(16), dp(16), dp(16))
|
||||
parent.addView(this, LinearLayout.LayoutParams(-1, -2))
|
||||
}
|
||||
}
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
savedInstanceState?.getString("month")?.let { month = YearMonth.parse(it) }
|
||||
savedInstanceState?.getString("selectedDate")?.let { selectedDate = LocalDate.parse(it) }
|
||||
if (savedInstanceState == null) intent.getStringExtra("selectedDate")?.let { value -> runCatching { selectedDate = LocalDate.parse(value); month = YearMonth.from(selectedDate) } }
|
||||
PlannerStore.migrate(this)
|
||||
render()
|
||||
if(savedInstanceState==null&&intent.hasExtra("widgetStyleId"))window.decorView.post { WidgetStyleDialog.show(this,intent.getIntExtra("widgetStyleId",-1)) }
|
||||
}
|
||||
override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState); outState.putString("month", month.toString()); outState.putString("selectedDate", selectedDate.toString()) }
|
||||
override fun onResume() {
|
||||
super.onResume(); render(); DutyWidget.updateAll(this); Reminders.reschedule(this)
|
||||
Holidays.schedule(this)
|
||||
Holidays.refresh(this) { success -> if (success) runOnUiThread { if (!isFinishing && !isDestroyed) render() } }
|
||||
SyncClient.schedule(this)
|
||||
SyncClient.foreground(this) { runOnUiThread { if (!isFinishing && !isDestroyed) render() } }
|
||||
UpdateChecker.check(this, fresh = true)
|
||||
}
|
||||
override fun onPause() { SyncClient.background(); super.onPause() }
|
||||
override fun onWindowFocusChanged(hasFocus: Boolean) {
|
||||
super.onWindowFocusChanged(hasFocus)
|
||||
// 첫 실행에서는 onResume보다 창 표시가 늦을 수 있다. 저장된 새 버전도 창이 준비된 뒤 안내한다.
|
||||
// 확인 간격과 나중에 알림 설정은 UpdateChecker가 유지하므로 초점 변경마다 통신하지 않는다.
|
||||
if (hasFocus) UpdateChecker.check(this)
|
||||
}
|
||||
|
||||
internal fun render() {
|
||||
// 다른 기기의 변경을 받더라도 사용자가 읽고 있던 위치를 유지한다.
|
||||
// 연결 확인과 공휴일 갱신이 연달아 끝나면 앞선 화면의 위치 복원이 아직 대기 중일 수 있다.
|
||||
// 이때 새 화면의 임시 0 위치를 읽으면 아래쪽 메뉴가 갑자기 맨 위로 돌아가므로 저장한 위치를 유지한다.
|
||||
if (!restoringScroll && ::content.isInitialized) scrollOffset = (content.parent as? ScrollView)?.scrollY ?: scrollOffset
|
||||
restoringScroll = true
|
||||
val generation = ++renderGeneration
|
||||
val schedule = ScheduleStore.load(this)
|
||||
val configured = ScheduleStore.isConfigured(this)
|
||||
val today = LocalDate.now()
|
||||
val people = People.all(this)
|
||||
val scroll = ScrollView(this).apply {
|
||||
isFillViewport = true; setBackgroundColor(0xFFF4F1EA.toInt())
|
||||
setOnScrollChangeListener { _, _, y, _, _ -> if (!restoringScroll && generation == renderGeneration) scrollOffset = y }
|
||||
}
|
||||
content = column().apply { setPadding(dp(16), dp(18), dp(16), dp(24)) }
|
||||
scroll.addView(content)
|
||||
// 최신 안드로이드의 화면 가장자리 표시에서도 상태 표시줄과 탐색 버튼에 내용이 가리지 않게 한다.
|
||||
// 구형 기기는 기존 여백 API를 사용한다. 앱의 최소 지원 버전에서도 같은 내용을 볼 수 있어야 한다.
|
||||
scroll.setOnApplyWindowInsetsListener { view, insets ->
|
||||
if (android.os.Build.VERSION.SDK_INT >= 30) {
|
||||
val bars = insets.getInsets(android.view.WindowInsets.Type.systemBars() or android.view.WindowInsets.Type.displayCutout())
|
||||
view.setPadding(bars.left, bars.top, bars.right, bars.bottom)
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
view.setPadding(insets.systemWindowInsetLeft, insets.systemWindowInsetTop, insets.systemWindowInsetRight, insets.systemWindowInsetBottom)
|
||||
}
|
||||
insets
|
||||
}
|
||||
setContentView(scroll)
|
||||
val brand = row()
|
||||
brand.addView(ImageView(this).apply { setImageResource(R.drawable.ic_calendar); contentDescription = null }, LinearLayout.LayoutParams(dp(32), dp(36)).apply { marginEnd = dp(10) })
|
||||
brand.addView(label("당직근무", 23f, ink, true), LinearLayout.LayoutParams(0, -2, 1f))
|
||||
brand.addView(button("옵션") { showOptions() }, LinearLayout.LayoutParams(-2, dp(44)))
|
||||
content.addView(brand)
|
||||
space(content, 8)
|
||||
content.addView(label(if (SyncClient.connected(this)) SyncClient.message else "나의 근무 기록 · 이 기기에 저장", 12f, muted))
|
||||
space(content, 20)
|
||||
val todayCard = card(content, 0xFFFFFEFA.toInt())
|
||||
todayCard.addView(label(today.format(DateTimeFormatter.ofPattern("M월 d일 EEEE", Locale.KOREAN)), 12f, muted))
|
||||
space(todayCard, 6)
|
||||
todayCard.addView(label(if (configured) "오늘은 ${schedule.shiftOn(today).title}" else "근무표를 설정해 주세요", 22f, if (configured) schedule.shiftColor(today) else ink, true))
|
||||
space(todayCard, 6)
|
||||
todayCard.addView(label(if (configured) "${schedule.pattern.size}일 반복 · 다음 날 ${schedule.shiftOn(today.plusDays(1)).title}" else "여기를 눌러 근무표를 설정하세요. 아래는 예시입니다.", 13f, muted))
|
||||
if (!configured) {
|
||||
todayCard.isFocusable = true
|
||||
todayCard.setOnClickListener { showSettings() }
|
||||
}
|
||||
space(content, 16)
|
||||
// 자주 쓰는 일정과 근무 설정을 달력 바로 앞에 둔다. 연결 관리가 날짜 확인을 밀어내지 않도록 한다.
|
||||
val quickActions = row()
|
||||
quickActions.addView(button("일정 추가", true) { planner.event(selectedDate) }, LinearLayout.LayoutParams(0, dp(48), 1f).apply { marginEnd = dp(8) })
|
||||
quickActions.addView(button("당직 기초 설정") { showSettings() }, LinearLayout.LayoutParams(0, dp(48), 1f))
|
||||
content.addView(quickActions)
|
||||
space(content, 14)
|
||||
val calendar = card(content, 0xFFFFFEFA.toInt())
|
||||
val navigation = row()
|
||||
navigation.addView(label("${month.year}. ${month.monthValue.toString().padStart(2, '0')}", 24f, ink, true), LinearLayout.LayoutParams(0, -2, 1f))
|
||||
navigation.addView(button("오늘") { month = YearMonth.now(); render() }, LinearLayout.LayoutParams(dp(62), dp(44)))
|
||||
calendar.addView(navigation)
|
||||
space(calendar, 12)
|
||||
val week = row()
|
||||
listOf("일", "월", "화", "수", "목", "금", "토").forEachIndexed { i, text ->
|
||||
week.addView(label(text, 13f, if (i == 0) 0xFFBD5163.toInt() else if (i == 6) schedule.saturdayColor else muted, true).apply { gravity = Gravity.CENTER }, LinearLayout.LayoutParams(0, dp(32), 1f))
|
||||
}
|
||||
calendar.addView(week)
|
||||
// 한 주를 7칸으로 나누고 같은 너비를 배정한다. 공휴일은 날짜 색상과 이름으로 함께 구분한다.
|
||||
// 앞뒤 달의 근무도 계산하지만 투명도를 낮춰 현재 보고 있는 달과 혼동하지 않게 한다.
|
||||
calendarDays(month).chunked(7).forEach { dates ->
|
||||
val cells = row()
|
||||
dates.forEach { date ->
|
||||
val shift = schedule.shiftOn(date)
|
||||
val holiday = Holidays.name(this, date)
|
||||
val lunar = if (schedule.showLunar) LunarDates.label(this, date) else null
|
||||
val events = PlannerStore.eventsOn(this, date)
|
||||
val personalDays = Anniversaries.on(this, date)
|
||||
val colleagues = People.onDuty(people, date)
|
||||
val inside = YearMonth.from(date) == month
|
||||
val cell = column().apply {
|
||||
gravity = Gravity.TOP or Gravity.CENTER_HORIZONTAL
|
||||
setPadding(0, dp(6), 0, 0)
|
||||
if (date == today) background = background(0xFFE8ECF3.toInt(), 3, accent)
|
||||
alpha = if (inside) 1f else 0.55f
|
||||
val dateColor = schedule.dateColor(date, holiday != null)
|
||||
addView(label(date.dayOfMonth.toString(), 18f, dateColor, true).apply { gravity = Gravity.CENTER })
|
||||
if (lunar != null) addView(label(lunar, 9f, muted).apply { gravity = Gravity.CENTER; maxLines = 1 })
|
||||
addView(label(shift.shortTitle, 12f, schedule.shiftColor(date), true).apply {
|
||||
gravity = Gravity.CENTER
|
||||
setPadding(dp(4), dp(2), dp(4), dp(2))
|
||||
background = background(schedule.shiftPale(date), 3)
|
||||
}, LinearLayout.LayoutParams(-2, -2).apply { topMargin = dp(3) })
|
||||
if (holiday != null) addView(label(if (holiday.contains("대체공휴일")) "대체휴일" else holiday.replace("기독탄신일", "성탄절").replace("1월 1일", "신정"), 10f, 0xFFBD5163.toInt(), true).apply {
|
||||
gravity = Gravity.CENTER; maxLines = 1; ellipsize = android.text.TextUtils.TruncateAt.END
|
||||
})
|
||||
if (events.isNotEmpty()) addView(label("일정 ${events.size}", 10f, 0xFF8B653C.toInt(), true).apply { gravity = Gravity.CENTER })
|
||||
if (personalDays.isNotEmpty()) addView(label(personalDays.first().getJSONObject("data").getString("title"), 10f, 0xFF896238.toInt(), true).apply { gravity = Gravity.CENTER; maxLines = 1; ellipsize = android.text.TextUtils.TruncateAt.END })
|
||||
colleagues.take(2).forEach { person -> addView(label(person.name, 10f, person.color, true).apply { gravity = Gravity.CENTER; maxLines = 1; ellipsize = android.text.TextUtils.TruncateAt.END }) }
|
||||
if (colleagues.size > 2) addView(label("외 ${colleagues.size - 2}명", 9f, muted).apply { gravity = Gravity.CENTER })
|
||||
// 좁은 칸에서 공휴일 이름이 생략돼도 날짜를 누르면 전체 이름을 확인할 수 있다.
|
||||
// 화면 읽기 기능에도 날짜와 전체 근무 이름 및 공휴일을 함께 전달한다.
|
||||
contentDescription = "${date.monthValue}월 ${date.dayOfMonth}일 ${shift.title} ${lunar.orEmpty()} ${holiday.orEmpty()} 일정 ${events.size}개. 기념일: ${personalDays.joinToString { it.getJSONObject("data").getString("title") }}. 함께 당직: ${colleagues.joinToString { it.name }}"
|
||||
isFocusable = true
|
||||
setOnClickListener {
|
||||
selectedDate = date
|
||||
render()
|
||||
val titles = (events.map { it.getJSONObject("data").getString("title") } + personalDays.map { "기념일 · " + it.getJSONObject("data").getString("title") }).toTypedArray()
|
||||
AlertDialog.Builder(this@MainActivity).setTitle("${date.monthValue}월 ${date.dayOfMonth}일 ${shift.title}")
|
||||
.setItems(titles) { _, index -> if (index < events.size) planner.event(date, events[index]) else anniversaries.edit(personalDays[index - events.size]) }
|
||||
.setPositiveButton("일정 추가") { _, _ -> planner.event(date) }
|
||||
.setNeutralButton("날짜 상세") { _, _ ->
|
||||
AlertDialog.Builder(this@MainActivity).setTitle(date.toString()).setMessage("나: ${shift.title}\n${holiday ?: "공휴일이 아닙니다."}\n일정 ${events.size}개\n\n" + people.joinToString("\n") { "${it.name}: ${it.schedule.shiftOn(date).title}" }).setPositiveButton("확인", null).show()
|
||||
}.setNegativeButton("닫기", null).show()
|
||||
}
|
||||
}
|
||||
cells.addView(cell, LinearLayout.LayoutParams(0, dp((if (people.isEmpty()) 103 else 148) + if (schedule.showLunar) 14 else 0), 1f))
|
||||
}
|
||||
calendar.addView(View(this).apply { setBackgroundColor(0xFFE6E4DC.toInt()) }, LinearLayout.LayoutParams(-1, dp(1)))
|
||||
calendar.addView(cells)
|
||||
}
|
||||
space(calendar, 12)
|
||||
val monthButtons = row()
|
||||
monthButtons.addView(button("이전 달") { month = month.minusMonths(1); render() }, LinearLayout.LayoutParams(0, dp(44), 1f).apply { marginEnd = dp(8) })
|
||||
monthButtons.addView(button("다음 달") { month = month.plusMonths(1); render() }, LinearLayout.LayoutParams(0, dp(44), 1f))
|
||||
calendar.addView(monthButtons)
|
||||
space(calendar, 14)
|
||||
calendar.addView(label("당직 · 일반 · 주간 · 오후 · 야간 · 비번 · 휴무", 11f, muted).apply { gravity = Gravity.CENTER })
|
||||
space(content, 16)
|
||||
val connection = card(content, 0xFFFFFEFA.toInt())
|
||||
connection.addView(label("웹과 연결", 16f, ink, true))
|
||||
if (SyncClient.connected(this)) {
|
||||
val tools = row()
|
||||
tools.addView(button("새로 불러오기") { SyncClient.sync(this, force = true) }, LinearLayout.LayoutParams(0, dp(48), 1f))
|
||||
tools.addView(button("소속 회사") { planner.openWebsite() }, LinearLayout.LayoutParams(0, dp(48), 1f))
|
||||
connection.addView(tools)
|
||||
PlannerStore.company(this)?.let { company -> connection.addView(label("소속 · ${company.getString("name")} · 근무표 공유", 12f, muted)) }
|
||||
connection.addView(label("저장된 자료 사용 · 월 1회 또는 변경 시 갱신", 11f, muted))
|
||||
}
|
||||
connection.addView(Switch(this).apply {
|
||||
text = "웹 연동 (선택)"; textSize = 14f; minHeight = dp(48); isChecked = SyncClient.enabled(this@MainActivity)
|
||||
setOnCheckedChangeListener { _, checked ->
|
||||
if (checked && !SyncClient.enabled(this@MainActivity)) { isChecked = false; planner.connection() }
|
||||
else if (!checked && SyncClient.enabled(this@MainActivity)) { SyncClient.disable(this@MainActivity); render() }
|
||||
}
|
||||
})
|
||||
space(content, 16)
|
||||
if (SyncClient.connected(this)) {
|
||||
val peopleCard = card(content)
|
||||
peopleCard.addView(label("함께 보는 근무표", 18f, ink, true))
|
||||
space(peopleCard, 6)
|
||||
peopleCard.addView(label("${selectedDate.monthValue}월 ${selectedDate.dayOfMonth}일 · 직접 등록한 근무표는 이름을 눌러 수정합니다.", 12f, muted))
|
||||
space(peopleCard, 8)
|
||||
people.forEach { person ->
|
||||
peopleCard.addView(button("${person.name} · ${person.schedule.shiftOn(selectedDate).title} (${person.schedule.pattern.size}일 반복${if (person.shared) " · 소속" else ""})") { if (person.shared) Toast.makeText(this, "소속 회원의 근무표는 본인만 수정할 수 있습니다.", Toast.LENGTH_LONG).show() else peopleEditor.edit(person) }.apply { setTextColor(person.color) }, LinearLayout.LayoutParams(-1, -2))
|
||||
}
|
||||
if (people.isEmpty()) peopleCard.addView(label("이름과 반복 근무를 등록하면 날짜별 당직을 함께 볼 수 있습니다.", 13f, muted))
|
||||
peopleCard.addView(button("함께 볼 사람 추가") { peopleEditor.edit() }, LinearLayout.LayoutParams(-1, dp(48)))
|
||||
space(content, 16)
|
||||
} else {
|
||||
val memberInfo = card(content)
|
||||
memberInfo.addView(label("함께 보는 근무표 · 회원 전용", 18f, ink, true))
|
||||
space(memberInfo, 8)
|
||||
memberInfo.addView(label("로그인하면 다른 사람의 근무표와 소속 근무표를 함께 볼 수 있습니다.", 13f, muted))
|
||||
space(memberInfo, 10)
|
||||
memberInfo.addView(button("로그인하고 함께 보기") { planner.connection() }, LinearLayout.LayoutParams(-1, dp(48)))
|
||||
space(content, 16)
|
||||
}
|
||||
val agenda = card(content)
|
||||
agenda.addView(label("${selectedDate.monthValue}월 ${selectedDate.dayOfMonth}일 일정", 18f, ink, true))
|
||||
space(agenda, 10)
|
||||
val selectedEvents = PlannerStore.eventsOn(this, selectedDate)
|
||||
val selectedDays = Anniversaries.on(this, selectedDate)
|
||||
if (selectedEvents.isEmpty() && selectedDays.isEmpty()) agenda.addView(label("등록된 일정이 없습니다. 날짜를 눌러 새 일정을 추가하세요.", 13f, muted))
|
||||
selectedDays.forEach { item ->
|
||||
val data = item.getJSONObject("data")
|
||||
agenda.addView(button("${data.getString("title")}\n${Anniversaries.description(data)}") { anniversaries.edit(item) }, LinearLayout.LayoutParams(-1, -2))
|
||||
}
|
||||
if (SyncClient.connected(this)) {
|
||||
agenda.addView(button("내 생일·기념일 관리") { anniversaries.list() }, LinearLayout.LayoutParams(-1, dp(48)))
|
||||
agenda.addView(label("내 계정에 보관 · 같은 계정으로 재로그인하면 복원", 12f, muted))
|
||||
}
|
||||
agenda.addView(button("알바·시간근무 추가") { planner.event(selectedDate, partTime = true) }, LinearLayout.LayoutParams(-1, dp(48)))
|
||||
selectedEvents.forEach { item ->
|
||||
val data = item.getJSONObject("data")
|
||||
val time = PlannerStore.timeSummary(data)
|
||||
agenda.addView(button("${data.getString("title")}\n$time") { planner.event(selectedDate, item) }, LinearLayout.LayoutParams(-1, dp(64)).apply { bottomMargin = dp(8) })
|
||||
}
|
||||
if (PlannerStore.conflictCount(this) > 0) {
|
||||
space(agenda, 12)
|
||||
agenda.addView(button("동시에 수정된 내용 확인", true) { planner.conflict() }, LinearLayout.LayoutParams(-1, dp(48)))
|
||||
}
|
||||
space(content, 16)
|
||||
val settings = card(content)
|
||||
settings.addView(label("나의 반복 근무", 18f, ink, true))
|
||||
space(settings, 8)
|
||||
settings.addView(label("주${schedule.workWeek}일제 · 토요일 ${if (schedule.workWeek == 5) "당직 외 휴무" else "기존 근무"}", 12f, muted))
|
||||
settings.addView(label(schedule.pattern.joinToString(" → ") { it.title }, 14f, muted))
|
||||
space(settings, 4)
|
||||
settings.addView(label(if (configured) "첫째 날: ${schedule.anchor}" else "시작 날짜를 저장하면 위젯에도 반영됩니다.", 12f, muted))
|
||||
space(settings, 14)
|
||||
settings.addView(button("당직 기초 설정", true) { showSettings() }, LinearLayout.LayoutParams(-1, dp(48)))
|
||||
space(settings, 8)
|
||||
settings.addView(button("옵션 · 날짜 색상과 음력") { showOptions() }, LinearLayout.LayoutParams(-1, dp(48)))
|
||||
space(content, 12)
|
||||
content.addView(button("위젯 꾸미기 · 투명도와 크기") { WidgetStyleDialog.show(this) }, LinearLayout.LayoutParams(-1, dp(48)))
|
||||
content.addView(button("홈 화면에 달력 추가") { pinWidget() }, LinearLayout.LayoutParams(-1, dp(52)))
|
||||
space(content, 10)
|
||||
content.addView(label("위젯은 앱을 닫아도 홈 화면에 표시됩니다.\n홈 화면을 길게 누른 뒤 ‘위젯’에서도 추가할 수 있습니다.", 12f, muted).apply { gravity = Gravity.CENTER })
|
||||
space(content, 20)
|
||||
val holidayInfo = card(content)
|
||||
holidayInfo.addView(label("대한민국 공휴일", 17f, ink, true))
|
||||
space(holidayInfo, 6)
|
||||
val updateTime = Holidays.updatedAt(this)
|
||||
val updated = if (updateTime == 0L) "기본 공휴일 자료를 사용 중입니다." else "최근 갱신: " + java.text.SimpleDateFormat("yyyy.MM.dd HH:mm", Locale.KOREAN).format(java.util.Date(updateTime))
|
||||
holidayInfo.addView(label(if (month.year in Holidays.years(this)) "공휴일과 대체공휴일을 자동으로 갱신합니다.\n$updated" + if (Holidays.usesSaved(this)) "\n서버에 보관된 정상 자료를 사용합니다." else "" else "${month.year}년 자료가 아직 제공되지 않았습니다.\n공휴일이 없는 것으로 판단하지 마세요.", 12f, muted))
|
||||
space(holidayInfo, 10)
|
||||
holidayInfo.addView(button("공휴일 새로고침") {
|
||||
Holidays.refresh(this, force = true) { success -> runOnUiThread {
|
||||
if (!isFinishing && !isDestroyed) {
|
||||
render()
|
||||
Toast.makeText(this, if (success) { if (Holidays.usesSaved(this)) "제공처 확인이 지연되어 저장된 공휴일을 표시합니다." else "공휴일을 갱신했습니다." } else "연결을 확인해 주세요. 저장된 공휴일을 계속 표시합니다.", Toast.LENGTH_LONG).show()
|
||||
}
|
||||
} }
|
||||
}, LinearLayout.LayoutParams(-1, dp(44)))
|
||||
space(holidayInfo, 8)
|
||||
holidayInfo.addView(label("음력 표시: 1900~2050년 · 한국 음력 기준", 11f, muted).apply {
|
||||
setOnClickListener { AlertDialog.Builder(this@MainActivity).setTitle("음력 자료 이용 조건").setMessage(assets.open("lunar-LICENSE.txt").bufferedReader().use { it.readText() }).setPositiveButton("확인", null).show() }
|
||||
})
|
||||
holidayInfo.addView(label("월력요항 기반 공개 자료 · holidays-kr\n공휴일에도 설정한 근무 순서는 유지됩니다.", 11f, muted).apply {
|
||||
setOnClickListener {
|
||||
val license = assets.open("holidays-LICENSE.txt").bufferedReader().use { it.readText() }
|
||||
AlertDialog.Builder(this@MainActivity).setTitle("공휴일 자료 출처")
|
||||
.setMessage("https://github.com/hyunbinseo/holidays-kr\n\n월력요항을 기반으로 관리되는 공개 자료입니다. 임시공휴일은 제공 자료가 갱신된 뒤 반영됩니다.\n\n$license")
|
||||
.setPositiveButton("확인", null).show()
|
||||
}
|
||||
})
|
||||
space(content, 24)
|
||||
content.addView(button("앱 업데이트 확인") { UpdateChecker.check(this, force = true) }, LinearLayout.LayoutParams(-1, dp(48)))
|
||||
space(content, 12)
|
||||
content.addView(label("제작자 블리어 (이창현)", 13f, muted).apply { gravity = Gravity.CENTER })
|
||||
space(content, 4)
|
||||
content.addView(label("당직근무 " + packageManager.getPackageInfo(packageName, 0).versionName, 11f, muted).apply { gravity = Gravity.CENTER })
|
||||
scroll.post {
|
||||
if (generation == renderGeneration) {
|
||||
scroll.scrollTo(0, scrollOffset)
|
||||
restoringScroll = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 기준일을 저장한 뒤 홈 화면에 위젯 추가를 요청한다. 최종 배치와 크기는 홈 화면 앱이 관리한다.
|
||||
* 바로 추가하는 기능을 지원하지 않는 홈 화면에서는 위젯 목록으로 추가하는 방법을 안내한다.
|
||||
* 별도 오버레이 권한을 요구하지 않으며 일반적인 안드로이드 위젯으로 동작한다.
|
||||
*/
|
||||
private fun pinWidget() {
|
||||
if (!ScheduleStore.isConfigured(this)) { showSettings(); return }
|
||||
val manager = getSystemService(AppWidgetManager::class.java)
|
||||
if (manager.isRequestPinAppWidgetSupported) {
|
||||
manager.requestPinAppWidget(ComponentName(this, DutyWidget::class.java), null, null)
|
||||
} else {
|
||||
AlertDialog.Builder(this).setTitle("홈 화면에 추가하기").setMessage("홈 화면의 빈 곳을 길게 누른 뒤 위젯 목록에서 ‘당직근무’를 선택해 주세요.").setPositiveButton("확인", null).show()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 설정 창에서는 저장값을 복사한 임시 목록만 바꾼다. 취소하면 기존 근무표에 영향을 주지 않는다.
|
||||
* 반복 일수가 늘어나면 추가된 날은 일반근무로 채운다. 줄어들면 뒤쪽 날을 잘라낸다.
|
||||
* 저장을 누를 때만 기준일과 전체 순서를 함께 반영하고 모든 홈 위젯을 갱신한다.
|
||||
*/
|
||||
private fun showSettings() {
|
||||
val current = ScheduleStore.load(this)
|
||||
var anchor = current.anchor
|
||||
val form = column().apply { setPadding(dp(20), dp(8), dp(20), dp(8)) }
|
||||
form.addView(label("근무 방식과 반복 순서 및 기준일을 정합니다.\n날짜 색상과 음력은 옵션에서 바꿀 수 있습니다.", 12f, muted))
|
||||
val patternEditor = ShiftPatternEditor(this, current.pattern, current.workWeek)
|
||||
form.addView(patternEditor)
|
||||
space(form, 12)
|
||||
form.addView(label("1일째에 해당하는 날짜", 14f, ink, true))
|
||||
lateinit var dateButton: Button
|
||||
dateButton = button(anchor.toString()) {
|
||||
DatePickerDialog(this, { _, year, monthIndex, day ->
|
||||
anchor = LocalDate.of(year, monthIndex + 1, day)
|
||||
dateButton.text = anchor.toString()
|
||||
}, anchor.year, anchor.monthValue - 1, anchor.dayOfMonth).show()
|
||||
}
|
||||
space(form, 8)
|
||||
form.addView(dateButton, LinearLayout.LayoutParams(-1, dp(48)))
|
||||
space(form, 10)
|
||||
form.addView(label("선택한 날짜부터 위 순서가 반복됩니다.\n비번과 휴일을 포함해 날짜 단위로 계산합니다.", 12f, muted))
|
||||
val scroll = ScrollView(this).apply { addView(form) }
|
||||
val dialog = AlertDialog.Builder(this).setTitle("당직 기초 설정").setView(scroll)
|
||||
.setNegativeButton("취소", null).setPositiveButton("저장", null).create()
|
||||
dialog.setOnShowListener {
|
||||
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener {
|
||||
// 기초 설정에서 표시 옵션을 저장하지 않는다. 창을 연 뒤 들어온 최신 표시 선택도 보존한다.
|
||||
runCatching { ScheduleStore.save(this, ScheduleStore.load(this).copy(anchor = anchor, pattern = patternEditor.pattern(), workWeek = patternEditor.workWeek())) }
|
||||
.onSuccess { render(); dialog.dismiss(); Toast.makeText(this, "근무표와 위젯을 갱신했습니다.", Toast.LENGTH_SHORT).show() }
|
||||
.onFailure { Toast.makeText(this, it.message ?: "입력 내용을 확인해 주세요.", Toast.LENGTH_LONG).show() }
|
||||
}
|
||||
}
|
||||
dialog.show()
|
||||
}
|
||||
|
||||
/** 계산 기준과 표시 선택을 분리한다. 취소는 저장하지 않으며 옵션 저장도 근무 순서를 바꾸지 않는다. */
|
||||
private fun showOptions() {
|
||||
val current = ScheduleStore.load(this)
|
||||
val form = column().apply { setPadding(dp(20), dp(8), dp(20), dp(16)) }
|
||||
form.addView(label("달력 표시", 16f, ink, true))
|
||||
form.addView(label(if (SyncClient.connected(this)) "${SyncClient.memberName(this)} 계정에 개인 설정을 보관합니다." else "현재 기기에 저장합니다. 회원 로그인 후 서버에 보관할 수 있습니다.", 12f, muted))
|
||||
form.addView(button("위젯 꾸미기 · 투명도와 크기") { WidgetStyleDialog.show(this) }, LinearLayout.LayoutParams(-1,dp(48)))
|
||||
form.addView(button("휴대폰 달력 연동") { deviceCalendar.open() }, LinearLayout.LayoutParams(-1,dp(48)))
|
||||
form.addView(label("앱과 홈 위젯에 함께 적용합니다.\n근무 순서와 기준일은 바뀌지 않습니다.", 12f, muted))
|
||||
fun choice(title: String, description: String, checked: Boolean): CheckBox {
|
||||
val option = CheckBox(this).apply { text = title; textSize = 14f; isChecked = checked; minHeight = dp(48) }
|
||||
space(form, 8); form.addView(option); form.addView(label(description, 12f, muted))
|
||||
return option
|
||||
}
|
||||
val weekday = choice("당직일은 평일색으로 표시", "주말·공휴일에도 당직 날짜는 평일색으로 표시합니다.", current.dutyAsWeekday)
|
||||
val off = choice("비번을 빨간색으로 표시", "비번 날짜와 비번 글씨를 빨간색으로 표시합니다.", current.offAsHoliday)
|
||||
val lunar = choice("음력 날짜 함께 보기", "양력 아래에 작은 글씨로 표시합니다. 윤달은 윤으로 구분합니다.", current.showLunar)
|
||||
val dialog = AlertDialog.Builder(this).setTitle("옵션").setView(ScrollView(this).apply { addView(form) })
|
||||
.setNegativeButton("취소", null).setPositiveButton("저장", null).create()
|
||||
dialog.setOnShowListener {
|
||||
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener {
|
||||
runCatching { ScheduleStore.saveDisplay(this, weekday.isChecked, lunar.isChecked, off.isChecked) }
|
||||
.onSuccess { render(); dialog.dismiss(); Toast.makeText(this, "표시 옵션을 저장했습니다.", Toast.LENGTH_SHORT).show() }
|
||||
.onFailure { Toast.makeText(this, it.message ?: "저장 공간을 확인해 주세요.", Toast.LENGTH_LONG).show() }
|
||||
}
|
||||
}
|
||||
dialog.show()
|
||||
}
|
||||
|
||||
override fun onRequestPermissionsResult(requestCode:Int,permissions:Array<out String>,grantResults:IntArray) {
|
||||
super.onRequestPermissionsResult(requestCode,permissions,grantResults)
|
||||
deviceCalendar.permissionResult(requestCode,grantResults)
|
||||
if(requestCode==Reminders.REQUEST_NOTIFY) {
|
||||
Reminders.reschedule(this)
|
||||
Toast.makeText(this,if(grantResults.firstOrNull()==android.content.pm.PackageManager.PERMISSION_GRANTED)"일정 알림을 켰습니다." else "알림을 허용하면 저장한 일정의 알림을 받을 수 있습니다.",Toast.LENGTH_LONG).show()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package kr.co.itosm.dutycalendar
|
||||
|
||||
import android.content.Context
|
||||
import org.json.JSONObject
|
||||
import java.time.LocalDate
|
||||
|
||||
/** 다른 사람의 근무표는 본인의 반복 설정과 분리한다. 등록은 이 캘린더의 메모이며 상대방 계정을 만들지 않는다. */
|
||||
data class PersonDuty(val id: String, val name: String, val colorKey: String, val schedule: Schedule, val shared: Boolean = false) {
|
||||
val color: Int get() = People.colors.getValue(colorKey).second
|
||||
}
|
||||
|
||||
object People {
|
||||
// 흰 배경에서도 이름을 읽을 수 있는 색을 사용한다. 색 이름과 실제 이름을 항상 같이 보여 준다.
|
||||
val colors = linkedMapOf(
|
||||
"BLUE" to ("파랑" to 0xFF365FAD.toInt()), "PURPLE" to ("보라" to 0xFF79459D.toInt()),
|
||||
"ORANGE" to ("주황" to 0xFFA75A14.toInt()), "PINK" to ("분홍" to 0xFFAD3D6E.toInt()),
|
||||
"TEAL" to ("청록" to 0xFF087C7C.toInt()), "BROWN" to ("갈색" to 0xFF795548.toInt()))
|
||||
fun all(context: Context): List<PersonDuty> {
|
||||
// 회원 연결이 꺼지면 보관 자료를 지우지 않고 표시에서 제외한다. 위젯도 이 경로를 사용한다.
|
||||
if (!SyncClient.connected(context)) return emptyList()
|
||||
return PlannerStore.items(context).filter { it.getString("kind") == "person" }.mapNotNull { item ->
|
||||
runCatching {
|
||||
val data = item.getJSONObject("data")
|
||||
PersonDuty(item.getString("id"), data.getString("name"), data.getString("color"),
|
||||
Schedule(LocalDate.parse(data.getString("anchor")), PlannerStore.listStrings(data.getJSONArray("pattern")).map(Shift::valueOf), data.optInt("workWeek", 6), data.optBoolean("dutyAsWeekday", false)))
|
||||
}.getOrNull()
|
||||
}.plus(shared(context)).sortedBy { it.name }
|
||||
}
|
||||
private fun shared(context: Context): List<PersonDuty> {
|
||||
val members = PlannerStore.company(context)?.optJSONArray("members") ?: return emptyList()
|
||||
return PlannerStore.list(members).filter { !it.optBoolean("isSelf") }.mapNotNull { person ->
|
||||
runCatching {
|
||||
val rotation = person.getJSONObject("rotation")
|
||||
PersonDuty("company:" + person.getString("id"), person.getString("name"), person.getString("color"),
|
||||
Schedule(LocalDate.parse(rotation.getString("anchor")), PlannerStore.listStrings(rotation.getJSONArray("pattern")).map(Shift::valueOf), rotation.optInt("workWeek", 6), rotation.optBoolean("dutyAsWeekday", false)), true)
|
||||
}.getOrNull()
|
||||
}
|
||||
}
|
||||
fun onDuty(people: List<PersonDuty>, date: LocalDate) = people.filter { it.schedule.shiftOn(date).working }
|
||||
fun validate(data: JSONObject) {
|
||||
require(data.optString("name").trim().length in 1..30) { "이름은 1~30자로 입력해 주세요." }
|
||||
require(data.optString("color") in colors) { "이름 표시 색상을 선택해 주세요." }
|
||||
require(!data.has("dutyAsWeekday") || data.get("dutyAsWeekday") is Boolean) { "당직일 날짜 표시 설정을 확인해 주세요." }
|
||||
require(!data.has("workWeek") || (data.get("workWeek") is Int && data.getInt("workWeek") in 5..6)) { "주5일제 또는 주6일제를 선택해 주세요." }
|
||||
val anchor = LocalDate.parse(data.getString("anchor"))
|
||||
require(anchor.year in 2000..2099) { "기준 날짜는 2000~2099년으로 지정해 주세요." }
|
||||
val pattern = PlannerStore.listStrings(data.getJSONArray("pattern"))
|
||||
require(pattern.size in 1..Schedule.MAX_DAYS && pattern.all { it in Shift.entries.map(Shift::name) }) { "근무 반복 설정을 확인해 주세요." }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package kr.co.itosm.dutycalendar
|
||||
|
||||
import android.app.Activity
|
||||
import android.app.AlertDialog
|
||||
import android.app.DatePickerDialog
|
||||
import android.graphics.Typeface
|
||||
import android.text.InputFilter
|
||||
import android.view.View
|
||||
import android.widget.*
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.time.LocalDate
|
||||
import java.util.UUID
|
||||
|
||||
/** 이름과 표시 색 및 개인별 반복 순서를 한 번에 저장한다. 편집 중의 값은 저장 전까지 원본에 반영하지 않는다. */
|
||||
class PeopleDialogs(private val activity: Activity, private val changed: () -> Unit) {
|
||||
private fun dp(n: Int) = (n * activity.resources.displayMetrics.density).toInt()
|
||||
fun edit(person: PersonDuty? = null) {
|
||||
if (!SyncClient.connected(activity)) { Toast.makeText(activity, "함께 보는 근무표는 회원 로그인 후 사용할 수 있습니다.", Toast.LENGTH_LONG).show(); return }
|
||||
var anchor = person?.schedule?.anchor ?: LocalDate.now()
|
||||
val form = LinearLayout(activity).apply { orientation = LinearLayout.VERTICAL; setPadding(dp(20), dp(8), dp(20), dp(16)) }
|
||||
fun caption(value: String) { form.addView(TextView(activity).apply { text = value; textSize = 14f; setPadding(0, dp(14), 0, dp(6)) }) }
|
||||
val name = EditText(activity).apply { hint = "함께 볼 사람의 이름"; contentDescription = "함께 볼 사람 이름"; setSingleLine(true); filters = arrayOf(InputFilter.LengthFilter(30)); setText(person?.name.orEmpty()) }
|
||||
caption("이름"); form.addView(name)
|
||||
val colors = People.colors.keys.toList()
|
||||
val preview = TextView(activity).apply { text = "이름 표시 색상"; textSize = 15f; setTypeface(typeface, Typeface.BOLD) }
|
||||
val color = Spinner(activity).apply {
|
||||
adapter = ArrayAdapter(activity, android.R.layout.simple_spinner_dropdown_item, People.colors.values.map { it.first })
|
||||
contentDescription = "이름 표시 색상"
|
||||
setSelection(colors.indexOf(person?.colorKey ?: "BLUE"))
|
||||
onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
|
||||
override fun onNothingSelected(parent: AdapterView<*>?) = Unit
|
||||
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { preview.setTextColor(People.colors.getValue(colors[position]).second) }
|
||||
}
|
||||
}
|
||||
caption("표시 색상"); form.addView(color); form.addView(preview)
|
||||
caption("당직 기초 설정")
|
||||
val patternEditor = ShiftPatternEditor(activity, person?.schedule?.pattern ?: Schedule.preset(3), person?.schedule?.workWeek ?: 6)
|
||||
form.addView(patternEditor)
|
||||
caption("첫째 날의 날짜")
|
||||
lateinit var dateButton: Button
|
||||
dateButton = Button(activity).apply { text = anchor.toString(); setOnClickListener {
|
||||
DatePickerDialog(activity, { _, y, m, d -> anchor = LocalDate.of(y, m + 1, d); dateButton.text = anchor.toString() }, anchor.year, anchor.monthValue - 1, anchor.dayOfMonth).show()
|
||||
} }; form.addView(dateButton)
|
||||
caption("표시 옵션")
|
||||
val weekdayDuty = CheckBox(activity).apply { text = "당직일은 평일색으로 표시"; textSize = 14f; minHeight = dp(48); isChecked = person?.schedule?.dutyAsWeekday ?: false }
|
||||
form.addView(weekdayDuty)
|
||||
caption("직접 입력한 근무표를 이 캘린더에서 함께 봅니다. 상대방에게 계정이나 접근 권한을 부여하지 않습니다.")
|
||||
val error = TextView(activity).apply { setTextColor(0xFFAD3D6E.toInt()) }; form.addView(error)
|
||||
val builder = AlertDialog.Builder(activity).setTitle(if (person == null) "함께 볼 사람 추가" else "${person.name} 근무표 수정")
|
||||
.setView(ScrollView(activity).apply { addView(form) }).setNegativeButton("취소", null).setPositiveButton("저장", null)
|
||||
if (person != null) builder.setNeutralButton("삭제", null)
|
||||
val dialog = builder.create()
|
||||
dialog.setOnShowListener {
|
||||
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener {
|
||||
try {
|
||||
val data = JSONObject().put("name", name.text.toString().trim()).put("color", colors[color.selectedItemPosition])
|
||||
.put("anchor", anchor.toString()).put("pattern", JSONArray(patternEditor.pattern().map { it.name })).put("workWeek", patternEditor.workWeek()).put("dutyAsWeekday", weekdayDuty.isChecked)
|
||||
PlannerStore.put(activity, person?.id ?: UUID.randomUUID().toString(), "person", data)
|
||||
SyncClient.sync(activity); changed(); dialog.dismiss()
|
||||
} catch (problem: Exception) { error.text = problem.message ?: "입력 내용을 확인해 주세요." }
|
||||
}
|
||||
if (person != null) dialog.getButton(AlertDialog.BUTTON_NEUTRAL).setOnClickListener {
|
||||
AlertDialog.Builder(activity).setTitle("${person.name} 근무표를 삭제할까요?").setMessage("이 캘린더에 직접 등록한 근무표만 삭제합니다.")
|
||||
.setNegativeButton("취소", null).setPositiveButton("삭제") { _, _ ->
|
||||
runCatching { PlannerStore.put(activity, person.id, "person", JSONObject(), true) }
|
||||
.onSuccess { SyncClient.sync(activity); changed(); dialog.dismiss() }
|
||||
.onFailure { error.text = "저장 공간을 확인해 주세요." }
|
||||
}.show()
|
||||
}
|
||||
}; dialog.show()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
package kr.co.itosm.dutycalendar
|
||||
|
||||
import android.app.Activity
|
||||
import android.app.AlertDialog
|
||||
import android.app.DatePickerDialog
|
||||
import android.app.TimePickerDialog
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.text.InputFilter
|
||||
import android.text.InputType
|
||||
import android.view.View
|
||||
import android.widget.*
|
||||
import org.json.JSONObject
|
||||
import java.time.LocalDate
|
||||
import java.time.LocalTime
|
||||
import java.util.Locale
|
||||
import java.util.UUID
|
||||
|
||||
/** 일정 편집과 기기 연결 창을 관리한다. 입력 검증에 실패하면 창을 닫지 않아 작성 내용을 보존한다. */
|
||||
class PlannerDialogs(private val activity: Activity, private val changed: () -> Unit) {
|
||||
private fun dp(value: Int) = (value * activity.resources.displayMetrics.density).toInt()
|
||||
private fun form() = LinearLayout(activity).apply { orientation = LinearLayout.VERTICAL; setPadding(dp(20), dp(8), dp(20), dp(12)) }
|
||||
private fun label(value: String) = TextView(activity).apply { text = value; textSize = 13f; setTextColor(0xFF65766F.toInt()); setPadding(0, dp(14), 0, dp(6)) }
|
||||
private fun field(hintText: String, max: Int) = EditText(activity).apply { hint = hintText; textSize = 16f; filters = arrayOf(InputFilter.LengthFilter(max)); setSingleLine(true) }
|
||||
private fun button(value: String, action: () -> Unit) = Button(activity).apply { text = value; isAllCaps = false; setOnClickListener { action() } }
|
||||
private fun safeUi(action: () -> Unit) { activity.runOnUiThread { if (!activity.isFinishing && !activity.isDestroyed) action() } }
|
||||
private fun toast(value: String) = Toast.makeText(activity, value, Toast.LENGTH_LONG).show()
|
||||
private fun categoryName(key: String) = when (key) { "PARTTIME" -> "알바·시간근무"; "WORK" -> "업무"; "LEAVE" -> "휴가·휴무"; else -> "개인 일정" }
|
||||
|
||||
fun event(date: LocalDate, item: JSONObject? = null, partTime: Boolean = false) {
|
||||
val data = item?.getJSONObject("data")
|
||||
var start = data?.getString("date")?.let(LocalDate::parse) ?: date
|
||||
var end = data?.getString("endDate")?.let(LocalDate::parse) ?: date
|
||||
var beginTime = data?.getString("startTime")?.let(LocalTime::parse) ?: LocalTime.of(9, 0)
|
||||
var endTime = data?.getString("endTime")?.let(LocalTime::parse) ?: LocalTime.of(10, 0)
|
||||
val form = form()
|
||||
val title = field("일정 이름 또는 근무지 · 예: 카페 오전", 120).apply { setText(data?.getString("title").orEmpty()); contentDescription = "일정 제목" }
|
||||
form.addView(label("제목")); form.addView(title)
|
||||
val categories = listOf("GENERAL", "WORK", "LEAVE", "PARTTIME")
|
||||
val category = Spinner(activity).apply { adapter = ArrayAdapter(activity, android.R.layout.simple_spinner_dropdown_item, categories.map(::categoryName)); setSelection(categories.indexOf(data?.optString("category") ?: if (partTime) "PARTTIME" else "GENERAL").coerceAtLeast(0)) }
|
||||
form.addView(label("일정 종류")); form.addView(category)
|
||||
fun pickDate(value: LocalDate, save: (LocalDate) -> Unit) {
|
||||
DatePickerDialog(activity, { _, year, month, day -> save(LocalDate.of(year, month + 1, day)) }, value.year, value.monthValue - 1, value.dayOfMonth).show()
|
||||
}
|
||||
lateinit var startButton: Button
|
||||
lateinit var endButton: Button
|
||||
startButton = button(start.toString()) { pickDate(start) { start = it; startButton.text = it.toString(); if (end < start) { end = start; endButton.text = end.toString() } } }
|
||||
endButton = button(end.toString()) { pickDate(end) { end = it; endButton.text = it.toString() } }
|
||||
form.addView(label("시작 날짜")); form.addView(startButton)
|
||||
form.addView(label("종료 날짜")); form.addView(endButton)
|
||||
val allDay = CheckBox(activity).apply { text = "하루 종일"; isChecked = data?.getBoolean("allDay") ?: !partTime }
|
||||
form.addView(allDay)
|
||||
val times = LinearLayout(activity).apply { orientation = LinearLayout.HORIZONTAL; visibility = if (allDay.isChecked) View.GONE else View.VISIBLE }
|
||||
lateinit var beginButton: Button
|
||||
lateinit var finishButton: Button
|
||||
beginButton = button("시작 $beginTime") { TimePickerDialog(activity, { _, hour, minute -> beginTime = LocalTime.of(hour, minute); beginButton.text = "시작 $beginTime" }, beginTime.hour, beginTime.minute, true).show() }
|
||||
finishButton = button("종료 $endTime") { TimePickerDialog(activity, { _, hour, minute -> endTime = LocalTime.of(hour, minute); finishButton.text = "종료 $endTime" }, endTime.hour, endTime.minute, true).show() }
|
||||
times.addView(beginButton, LinearLayout.LayoutParams(0, dp(48), 1f)); times.addView(finishButton, LinearLayout.LayoutParams(0, dp(48), 1f)); form.addView(times)
|
||||
allDay.setOnCheckedChangeListener { _, checked -> times.visibility = if (checked) View.GONE else View.VISIBLE }
|
||||
category.onItemSelectedListener=object:AdapterView.OnItemSelectedListener {
|
||||
override fun onNothingSelected(parent:AdapterView<*>?) {}
|
||||
override fun onItemSelected(parent:AdapterView<*>?,view:View?,position:Int,id:Long) {
|
||||
val timed=categories[position]=="PARTTIME";allDay.isEnabled=!timed
|
||||
if(timed)allDay.isChecked=false
|
||||
}
|
||||
}
|
||||
form.addView(label("근무지와 시간대가 다르면 일정을 각각 추가하세요. 밤을 넘기는 근무는 종료 날짜를 다음 날로 정합니다."))
|
||||
val repeatKeys=listOf("NONE","DAILY","WEEKLY","MONTHLY","YEARLY")
|
||||
val repeat=Spinner(activity).apply{adapter=ArrayAdapter(activity,android.R.layout.simple_spinner_dropdown_item,listOf("반복 없음","매일","매주","매월","매년"));setSelection(repeatKeys.indexOf(data?.optString("repeat","NONE")?:"NONE").coerceAtLeast(0));contentDescription="일정 반복"}
|
||||
form.addView(label("반복"));form.addView(repeat)
|
||||
val repeatUntil=field("종료일 없음 · 예: 2027-12-31",10).apply{setText(data?.optString("repeatUntil").orEmpty());contentDescription="반복 종료일"}
|
||||
form.addView(label("반복 종료일 (선택)"));form.addView(repeatUntil)
|
||||
form.addView(label("반복 일정 수정과 삭제는 전체 반복에 적용됩니다. 매월 31일이나 매년 2월 29일이 없는 달에는 말일에 표시합니다."))
|
||||
val reminder=Spinner(activity).apply{adapter=ArrayAdapter(activity,android.R.layout.simple_spinner_dropdown_item,Reminders.labels);setSelection(Reminders.minutes.indexOf(data?.optInt("reminderMinutes",-1)?:-1).coerceAtLeast(0));contentDescription="일정 알림"}
|
||||
form.addView(label("휴대폰 알림"));form.addView(reminder)
|
||||
form.addView(label("하루 종일 일정은 오전 9시 기준입니다. 알림 허용이 필요하며 절전 중에는 늦게 울릴 수 있습니다. 웹에서는 알림 선택만 저장합니다."))
|
||||
val notes = field("장소나 기억할 내용", 2000).apply { setSingleLine(false); minLines = 2; inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_MULTI_LINE; setText(data?.getString("notes").orEmpty()); contentDescription = "일정 메모" }
|
||||
form.addView(label("메모")); form.addView(notes)
|
||||
if(item!=null)form.addView(button("휴대폰 달력에 보내기") {
|
||||
val saved=item.getJSONObject("data")
|
||||
DeviceCalendar.send(activity,saved,PlannerStore.eventRule(saved).occurrenceOn(date)?:LocalDate.parse(saved.getString("date")))
|
||||
})
|
||||
if(item!=null)form.addView(label("저장된 일정의 선택한 날짜 한 회차를 달력 앱으로 보냅니다. 바꾼 내용은 먼저 저장해 주세요."))
|
||||
val error = label("").apply { setTextColor(0xFFB5475B.toInt()) }; form.addView(error)
|
||||
val dialog = AlertDialog.Builder(activity).setTitle(if (item == null) "일정 추가" else "일정 수정").setView(ScrollView(activity).apply { addView(form) }).setNegativeButton("취소", null).setPositiveButton("저장", null)
|
||||
if (item != null) dialog.setNeutralButton("삭제", null)
|
||||
val window = dialog.create()
|
||||
window.setOnShowListener {
|
||||
window.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener {
|
||||
try {
|
||||
val value = JSONObject().put("title", title.text.toString().trim()).put("notes", notes.text.toString()).put("category", categories[category.selectedItemPosition])
|
||||
.put("date", start.toString()).put("endDate", end.toString()).put("allDay", allDay.isChecked).put("startTime", beginTime.toString()).put("endTime", endTime.toString())
|
||||
.put("repeat",repeatKeys[repeat.selectedItemPosition]).put("repeatUntil",if(repeat.selectedItemPosition==0)"" else repeatUntil.text.toString().trim()).put("reminderMinutes",Reminders.minutes[reminder.selectedItemPosition])
|
||||
PlannerStore.put(activity, item?.getString("id") ?: UUID.randomUUID().toString(), "event", value)
|
||||
changed(); SyncClient.sync(activity); window.dismiss(); toast("일정을 저장했습니다.")
|
||||
if(Reminders.minutes[reminder.selectedItemPosition]>=0)Reminders.requestPermission(activity)
|
||||
} catch (problem: Exception) { error.text = problem.message ?: "일정 내용을 확인해 주세요." }
|
||||
}
|
||||
if (item != null) window.getButton(AlertDialog.BUTTON_NEUTRAL).setOnClickListener {
|
||||
AlertDialog.Builder(activity).setTitle("일정을 삭제할까요?").setMessage("연결된 웹과 다른 기기에도 반영됩니다.").setNegativeButton("취소", null).setPositiveButton("삭제") { _, _ ->
|
||||
runCatching { PlannerStore.put(activity, item.getString("id"), "event", JSONObject(), deleted = true) }
|
||||
.onSuccess { changed(); SyncClient.sync(activity); window.dismiss(); toast("일정을 삭제했습니다.") }
|
||||
.onFailure { toast("저장 공간을 확인해 주세요.") }
|
||||
}.show()
|
||||
}
|
||||
}
|
||||
window.show()
|
||||
}
|
||||
|
||||
fun connection() {
|
||||
if (SyncClient.enabled(activity)) {
|
||||
AlertDialog.Builder(activity).setTitle("웹 연동 사용 중 · ${SyncClient.memberName(activity)}")
|
||||
.setItems(arrayOf("새로 불러오기", "홈페이지 열기", "회원 다시 로그인", "웹 연동 끄기")) { _, index ->
|
||||
when (index) {
|
||||
0 -> SyncClient.sync(activity, force = true)
|
||||
1 -> openWebsite()
|
||||
2 -> memberLogin()
|
||||
3 -> { SyncClient.disable(activity); changed(); toast("웹 연동을 껐습니다. 기기의 일정은 그대로 유지됩니다.") }
|
||||
}
|
||||
}.setNegativeButton("닫기", null).show()
|
||||
return
|
||||
}
|
||||
AlertDialog.Builder(activity).setTitle("웹 연동 선택")
|
||||
.setMessage("기본 기능과 홈 위젯은 회원가입 없이 사용할 수 있습니다.\n\n웹에서도 일정을 쓰려면 홈페이지에 가입한 회원으로 로그인하세요. 로그인하면 이 기기의 일정과 함께 볼 사람의 근무표를 서버와 동기화합니다.")
|
||||
.setPositiveButton("회원 로그인") { _, _ -> memberLogin() }
|
||||
.setNeutralButton("홈페이지 회원가입") { _, _ -> openWebsite() }
|
||||
.setNegativeButton("기기에서만 사용", null).show()
|
||||
}
|
||||
fun openWebsite() { activity.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(SyncClient.WEB_URL))) }
|
||||
private fun memberLogin() {
|
||||
val body = form()
|
||||
val username = field("홈페이지 아이디", 32).apply { contentDescription = "회원 아이디"; inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD }
|
||||
val password = field("비밀번호", 128).apply { contentDescription = "회원 비밀번호"; inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD }
|
||||
val error = label("").apply { setTextColor(0xFFAD3D6E.toInt()) }
|
||||
body.addView(label("아이디")); body.addView(username); body.addView(label("비밀번호")); body.addView(password); body.addView(error)
|
||||
val dialog = AlertDialog.Builder(activity).setTitle("회원 로그인과 웹 연동").setView(body).setPositiveButton("로그인하고 연동", null).setNegativeButton("취소", null).create()
|
||||
dialog.setOnShowListener { dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener {
|
||||
val name = username.text.toString().trim().lowercase(Locale.ROOT)
|
||||
val value = password.text.toString()
|
||||
if (name.isBlank() || value.isEmpty()) { error.text = "아이디와 비밀번호를 입력해 주세요."; return@setOnClickListener }
|
||||
dialog.getButton(AlertDialog.BUTTON_POSITIVE).isEnabled = false
|
||||
dialog.getButton(AlertDialog.BUTTON_NEGATIVE).isEnabled = false
|
||||
dialog.setCancelable(false)
|
||||
// 비밀번호는 요청이 끝나면 입력창에서 지운다. 연결에 필요한 암호화된 인증값만 기기에 남긴다.
|
||||
SyncClient.connect(activity, name, value) { problem -> safeUi {
|
||||
password.text.clear()
|
||||
if (problem == null) { dialog.dismiss(); toast("웹 연동을 켰습니다."); activity.recreate() }
|
||||
else { error.text = problem; dialog.setCancelable(true); dialog.getButton(AlertDialog.BUTTON_POSITIVE).isEnabled = true; dialog.getButton(AlertDialog.BUTTON_NEGATIVE).isEnabled = true }
|
||||
} }
|
||||
} }; dialog.show()
|
||||
}
|
||||
|
||||
fun conflict() {
|
||||
val (local, remote) = PlannerStore.conflict(activity) ?: return
|
||||
fun describe(item: JSONObject?): String {
|
||||
if (item == null || item.optBoolean("deleted")) return "삭제된 일정"
|
||||
val data = item.getJSONObject("data")
|
||||
if (item.getString("kind") == "anniversary") return "${data.getString("title")}\n${Anniversaries.description(data)}\n${data.getString("notes")}"
|
||||
if (item.getString("kind") == "preferences") return "당직일 평일색: ${if (data.getBoolean("dutyAsWeekday")) "켜짐" else "꺼짐"}\n비번 빨간색: ${if (data.getBoolean("offAsHoliday")) "켜짐" else "꺼짐"}\n음력 표시: ${if (data.getBoolean("showLunar")) "켜짐" else "꺼짐"}"
|
||||
if (item.getString("kind") == "person") return "${data.getString("name")} · ${People.colors.getValue(data.getString("color")).first}\n첫째 날: ${data.getString("anchor")}\n" + PlannerStore.listStrings(data.getJSONArray("pattern")).joinToString(" → ") { Shift.valueOf(it).title }
|
||||
if (item.getString("kind") == "rotation") return "첫째 날: ${data.getString("anchor")}\n" + (0 until data.getJSONArray("pattern").length()).joinToString(" → ") { Shift.valueOf(data.getJSONArray("pattern").getString(it)).title }
|
||||
return "${data.getString("title")}\n${data.getString("date")} ~ ${data.getString("endDate")}\n" + (if (data.getBoolean("allDay")) "하루 종일" else "${data.getString("startTime")} ~ ${data.getString("endTime")}") + "\n${categoryName(data.getString("category"))}\n${data.getString("notes")}"
|
||||
}
|
||||
AlertDialog.Builder(activity).setTitle("동시에 수정된 내용").setMessage("이 기기의 내용\n${describe(local)}\n\n서버의 최신 내용\n${describe(remote)}\n\n보관할 내용을 선택해 주세요.")
|
||||
.setPositiveButton("내 내용 저장") { _, _ -> PlannerStore.resolve(activity, true); changed(); SyncClient.sync(activity) }
|
||||
.setNeutralButton("서버 내용 사용") { _, _ -> PlannerStore.resolve(activity, false); changed(); SyncClient.sync(activity) }
|
||||
.setNegativeButton("나중에", null).show()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
package kr.co.itosm.dutycalendar
|
||||
|
||||
import android.content.Context
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.time.LocalDate
|
||||
import java.time.LocalDateTime
|
||||
import java.util.UUID
|
||||
|
||||
/**
|
||||
* 서버의 마지막 원본과 전송 대기 변경을 나누어 보관한다. 화면에서는 두 내용을 합쳐 읽는다.
|
||||
* 오프라인에서 저장한 일정은 전송 대기 목록에 남으며 서버 응답을 받은 변경 번호만 지운다.
|
||||
* 일정마다 서버 버전을 기록하므로 서로 다른 날짜를 고친 경우에는 독립적으로 반영할 수 있다.
|
||||
* 같은 항목을 함께 고친 경우에는 두 내용을 보존하고 사용자가 선택할 때까지 전송을 보류한다.
|
||||
*/
|
||||
object PlannerStore {
|
||||
private fun preferences(context: Context) = context.getSharedPreferences("planner", Context.MODE_PRIVATE)
|
||||
private fun read(context: Context): JSONObject = runCatching {
|
||||
JSONObject(preferences(context).getString("document", "{}")!!)
|
||||
}.getOrDefault(JSONObject()).apply {
|
||||
if (!has("state")) put("state", JSONObject().put("revision", 0).put("items", JSONArray()))
|
||||
if (!has("pending")) put("pending", JSONArray())
|
||||
if (!has("conflicts")) put("conflicts", JSONArray())
|
||||
}
|
||||
private fun save(context: Context, document: JSONObject) {
|
||||
// 앱이 저장됐다고 알리기 전에 디스크 반영을 확인한다. 실패한 저장을 성공으로 표시하지 않는다.
|
||||
check(preferences(context).edit().putString("document", document.toString()).commit()) { "저장 공간을 확인해 주세요." }
|
||||
}
|
||||
fun list(array: JSONArray): List<JSONObject> = (0 until array.length()).map { array.getJSONObject(it) }
|
||||
private fun strings(array: JSONArray) = (0 until array.length()).map { array.getString(it) }
|
||||
fun listStrings(array: JSONArray) = strings(array)
|
||||
@Synchronized fun pendingCount(context: Context) = read(context).getJSONArray("pending").length()
|
||||
@Synchronized fun conflictCount(context: Context) = read(context).getJSONArray("conflicts").length()
|
||||
@Synchronized fun revision(context: Context) = read(context).getJSONObject("state").optLong("revision")
|
||||
@Synchronized fun refreshedAt(context: Context) = read(context).optLong("refreshedAt")
|
||||
@Synchronized fun companyVersion(context: Context) = read(context).getJSONObject("state").optString("companyVersion")
|
||||
@Synchronized fun company(context: Context): JSONObject? = read(context).getJSONObject("state").optJSONObject("company")
|
||||
@Synchronized fun calendarId(context: Context) = read(context).getJSONObject("state").optString("calendarId")
|
||||
@Synchronized fun operations(context: Context): JSONArray {
|
||||
val document = read(context)
|
||||
val conflicts = strings(document.getJSONArray("conflicts"))
|
||||
return JSONArray(list(document.getJSONArray("pending")).filter { it.getString("changeId") !in conflicts }.take(100))
|
||||
}
|
||||
@Synchronized fun items(context: Context): List<JSONObject> {
|
||||
val document = read(context)
|
||||
val combined = list(document.getJSONObject("state").getJSONArray("items")).associateBy { it.getString("id") }.toMutableMap()
|
||||
list(document.getJSONArray("pending")).forEach { combined[it.getString("id")] = it }
|
||||
return combined.values.filter { !it.getBoolean("deleted") }
|
||||
}
|
||||
fun eventsOn(context: Context, date: LocalDate) = items(context).filter {
|
||||
it.getString("kind") == "event" && eventRule(it.getJSONObject("data")).occurrenceOn(date) != null
|
||||
}.sortedWith(compareBy<JSONObject> { !it.getJSONObject("data").getBoolean("allDay") }.thenBy { it.getJSONObject("data").getString("startTime") }.thenBy { it.getJSONObject("data").getString("title") })
|
||||
|
||||
@Synchronized fun put(context: Context, id: String, kind: String, data: JSONObject, deleted: Boolean = false) {
|
||||
if (kind == "event" && !deleted) validateEvent(data)
|
||||
if (kind == "anniversary") {
|
||||
require(SyncClient.connected(context)) { "기념일은 회원 로그인 후 사용할 수 있습니다." }
|
||||
if (!deleted) {
|
||||
Anniversaries.validate(data)
|
||||
require(items(context).count { it.getString("kind") == "anniversary" && it.getString("id") != id } < 200) { "기념일은 200개까지 등록할 수 있습니다." }
|
||||
}
|
||||
}
|
||||
if (kind == "person" && !deleted) {
|
||||
People.validate(data)
|
||||
require(items(context).count { it.getString("kind") == "person" && it.getString("id") != id } < 20) { "함께 볼 사람은 20명까지 등록할 수 있습니다." }
|
||||
}
|
||||
val document = read(context)
|
||||
val pending = list(document.getJSONArray("pending"))
|
||||
val previous = pending.find { it.getString("id") == id }
|
||||
val remote = list(document.getJSONObject("state").getJSONArray("items")).find { it.getString("id") == id }
|
||||
val operation = JSONObject().put("id", id).put("kind", kind).put("data", data).put("deleted", deleted)
|
||||
.put("baseVersion", previous?.getLong("baseVersion") ?: remote?.getLong("version") ?: 0L).put("changeId", UUID.randomUUID().toString())
|
||||
document.put("pending", JSONArray(pending.filter { it.getString("id") != id } + operation))
|
||||
document.put("conflicts", JSONArray(strings(document.getJSONArray("conflicts")).filter { it != previous?.getString("changeId") }))
|
||||
save(context, document)
|
||||
DutyWidget.updateAll(context)
|
||||
Reminders.reschedule(context)
|
||||
}
|
||||
|
||||
@Synchronized fun accept(context: Context, state: JSONObject, result: JSONObject? = null) {
|
||||
val document = read(context)
|
||||
val previousCalendar = document.getJSONObject("state").optString("calendarId")
|
||||
require(previousCalendar.isBlank() || previousCalendar == state.getString("calendarId")) { "다른 캘린더의 자료로 바꿀 수 없습니다. 원래 캘린더의 연결 코드를 사용해 주세요." }
|
||||
val accepted = result?.optJSONArray("accepted")?.let(::strings).orEmpty()
|
||||
val remaining = list(document.getJSONArray("pending")).filter { it.getString("changeId") !in accepted }
|
||||
val ids = remaining.map { it.getString("changeId") }
|
||||
document.put("state", state).put("pending", JSONArray(remaining)).put("refreshedAt", System.currentTimeMillis())
|
||||
document.put("conflicts", JSONArray((strings(document.getJSONArray("conflicts")) + result?.optJSONArray("conflicts")?.let(::strings).orEmpty()).distinct().filter { it in ids }))
|
||||
save(context, document)
|
||||
applyRotation(context)
|
||||
DutyWidget.updateAll(context)
|
||||
Reminders.reschedule(context)
|
||||
}
|
||||
|
||||
// 기존 0.1 버전의 반복 설정은 최초 한 번만 새 저장 구조로 옮긴다. 기존 파일도 그대로 유지한다.
|
||||
@Synchronized fun migrate(context: Context) {
|
||||
if (preferences(context).getBoolean("migrated", false)) return
|
||||
if (ScheduleStore.isConfigured(context)) queueRotation(context, ScheduleStore.load(context))
|
||||
preferences(context).edit().putBoolean("migrated", true).commit()
|
||||
}
|
||||
fun queueRotation(context: Context, schedule: Schedule) {
|
||||
put(context, "rotation", "rotation", JSONObject().put("anchor", schedule.anchor.toString()).put("pattern", JSONArray(schedule.pattern.map { it.name })).put("workWeek", schedule.workWeek).put("dutyAsWeekday", schedule.dutyAsWeekday).put("showLunar", schedule.showLunar).put("offAsHoliday", schedule.offAsHoliday))
|
||||
}
|
||||
fun queuePreferences(context: Context, schedule: Schedule) {
|
||||
put(context, "preferences", "preferences", JSONObject().put("dutyAsWeekday", schedule.dutyAsWeekday)
|
||||
.put("showLunar", schedule.showLunar).put("offAsHoliday", schedule.offAsHoliday))
|
||||
}
|
||||
private fun applyRotation(context: Context) {
|
||||
val items = items(context)
|
||||
val options = items.find { it.getString("kind") == "preferences" }?.getJSONObject("data")
|
||||
items.find { it.getString("kind") == "rotation" }?.getJSONObject("data")?.let { data ->
|
||||
val display = options ?: data
|
||||
ScheduleStore.save(context, Schedule(LocalDate.parse(data.getString("anchor")), strings(data.getJSONArray("pattern")).map(Shift::valueOf), data.optInt("workWeek", 6), display.optBoolean("dutyAsWeekday", false), display.optBoolean("showLunar", false), display.optBoolean("offAsHoliday", false)), fromSync = true)
|
||||
}
|
||||
if (options != null) {
|
||||
ScheduleStore.saveDisplay(context, options.getBoolean("dutyAsWeekday"), options.getBoolean("showLunar"), options.getBoolean("offAsHoliday"), fromSync = true)
|
||||
}
|
||||
}
|
||||
@Synchronized fun conflict(context: Context): Pair<JSONObject, JSONObject?>? {
|
||||
val document = read(context)
|
||||
val conflicts = strings(document.getJSONArray("conflicts"))
|
||||
val pending = list(document.getJSONArray("pending")).find { it.getString("changeId") in conflicts } ?: return null
|
||||
return pending to list(document.getJSONObject("state").getJSONArray("items")).find { it.getString("id") == pending.getString("id") }
|
||||
}
|
||||
@Synchronized fun resolve(context: Context, useLocal: Boolean) {
|
||||
val (operation, remote) = conflict(context) ?: return
|
||||
val document = read(context)
|
||||
val pending = list(document.getJSONArray("pending")).filter { it.getString("changeId") != operation.getString("changeId") }.toMutableList()
|
||||
document.put("conflicts", JSONArray(strings(document.getJSONArray("conflicts")).filter { it != operation.getString("changeId") }))
|
||||
if (useLocal) pending.add(operation.put("baseVersion", remote?.getLong("version") ?: 0L).put("changeId", UUID.randomUUID().toString()))
|
||||
document.put("pending", JSONArray(pending))
|
||||
save(context, document)
|
||||
applyRotation(context)
|
||||
DutyWidget.updateAll(context)
|
||||
Reminders.reschedule(context)
|
||||
}
|
||||
fun validateEvent(data: JSONObject) {
|
||||
require(data.getString("title").trim().length in 1..120) { "제목을 1자부터 120자까지 입력해 주세요." }
|
||||
require(data.getString("notes").length <= 2000) { "메모는 2000자까지 입력할 수 있습니다." }
|
||||
val start = LocalDate.parse(data.getString("date")); val end = LocalDate.parse(data.getString("endDate"))
|
||||
require(start.year in 2000..2099 && end.year in 2000..2099 && !end.isBefore(start) && !end.isAfter(start.plusDays(366))) { "종료 날짜를 시작 이후 366일 이내로 지정해 주세요." }
|
||||
require(data.optString("category") != "PARTTIME" || !data.getBoolean("allDay")) { "알바·시간근무는 시간을 지정해 주세요." }
|
||||
if (!data.getBoolean("allDay")) require(LocalDateTime.parse("${start}T${data.getString("startTime")}").isBefore(LocalDateTime.parse("${end}T${data.getString("endTime")}"))) { "종료 시간은 시작 시간보다 늦어야 합니다." }
|
||||
eventRule(data)
|
||||
require(data.optInt("reminderMinutes", -1) in listOf(-1,0,10,30,60,1440)) { "알림 시간을 확인해 주세요." }
|
||||
}
|
||||
fun timeSummary(data: JSONObject): String {
|
||||
if(data.getBoolean("allDay"))return "하루 종일"
|
||||
val days=java.time.temporal.ChronoUnit.DAYS.between(LocalDate.parse(data.getString("date")),LocalDate.parse(data.getString("endDate")))
|
||||
val finish=when(days){0L->"";1L->"다음 날 ";else->"${days}일 뒤 "}
|
||||
return "${data.getString("startTime")} – $finish${data.getString("endTime")}"+(if(data.optString("category")=="PARTTIME")" · 알바" else "")
|
||||
}
|
||||
fun eventRule(data: JSONObject) = EventRepeat(LocalDate.parse(data.getString("date")), LocalDate.parse(data.getString("endDate")),data.optString("repeat","NONE"),data.optString("repeatUntil").takeIf{it.isNotBlank()}?.let(LocalDate::parse))
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package kr.co.itosm.dutycalendar
|
||||
|
||||
import android.app.job.JobParameters
|
||||
import android.app.job.JobService
|
||||
|
||||
/** 월별 자료 갱신과 저장 대기 변경의 일회성 전송을 구분한다. 절전 중에는 실행이 늦어질 수 있다. */
|
||||
class PlannerSyncService : JobService() {
|
||||
override fun onStartJob(params: JobParameters): Boolean {
|
||||
// 운영체제가 예약을 앞당기거나 다시 실행해도 마지막 수신 시각을 확인한다.
|
||||
// 강제 수신은 사용자의 새로 불러오기와 실제 변경 알림에서만 요청한다.
|
||||
SyncClient.sync(applicationContext) { success -> jobFinished(params, !success) }
|
||||
return true
|
||||
}
|
||||
override fun onStopJob(params: JobParameters) = true
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package kr.co.itosm.dutycalendar
|
||||
|
||||
/** 전체 자료는 한 달 동안 재사용한다. 수동 요청과 서버의 변경 알림은 주기와 관계없이 반영한다. */
|
||||
object RefreshPolicy {
|
||||
const val MONTH_MS = 30L * 24 * 60 * 60 * 1000
|
||||
// 안드로이드의 주기 작업은 전체 기간의 5% 이상을 실행 허용 구간으로 요구한다.
|
||||
const val FLEX_MS = MONTH_MS / 20
|
||||
fun needsRefresh(lastFetched: Long, now: Long, requested: Boolean = false): Boolean =
|
||||
requested || lastFetched <= 0L || now < lastFetched || now - lastFetched >= MONTH_MS
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package kr.co.itosm.dutycalendar
|
||||
|
||||
import android.Manifest
|
||||
import android.app.*
|
||||
import android.content.*
|
||||
import android.content.pm.PackageManager
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import org.json.JSONObject
|
||||
import java.time.*
|
||||
import java.util.concurrent.Executors
|
||||
|
||||
/** 알림은 휴대폰에 저장된 일정으로 예약한다. 서버는 개인 자료를 보관하고 실제 알림은 각 기기가 보낸다.
|
||||
* 가장 가까운 시각 하나만 예약해 일정 개수만큼 시스템 예약을 만들지 않는다. 실행 후 다음 시각을 예약한다.
|
||||
* 별도 정확한 알람 권한을 강요하지 않는다. 절전 중에는 시스템 정책에 따라 늦게 전달될 수 있다.
|
||||
*/
|
||||
object Reminders {
|
||||
val minutes=listOf(-1,0,10,30,60,1440)
|
||||
val labels=listOf("알림 없음","시작 시간","10분 전","30분 전","1시간 전","하루 전")
|
||||
const val REQUEST_NOTIFY=7202
|
||||
private const val ACTION="kr.co.itosm.dutycalendar.REMIND"
|
||||
private val executor=Executors.newSingleThreadExecutor()
|
||||
data class Plan(val id:String,val date:LocalDate,val at:Long,val title:String)
|
||||
fun requestPermission(activity:Activity) {
|
||||
if(Build.VERSION.SDK_INT>=33&&activity.checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS)!=PackageManager.PERMISSION_GRANTED)
|
||||
activity.requestPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS),REQUEST_NOTIFY)
|
||||
else reschedule(activity)
|
||||
}
|
||||
private fun allowed(context:Context)= (Build.VERSION.SDK_INT<33||context.checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS)==PackageManager.PERMISSION_GRANTED)&&context.getSystemService(NotificationManager::class.java).areNotificationsEnabled()
|
||||
fun plans(context:Context,after:Long):List<Plan> {
|
||||
val zone=ZoneId.systemDefault();val today=Instant.ofEpochMilli(after).atZone(zone).toLocalDate()
|
||||
return PlannerStore.items(context).mapNotNull{item->runCatching{
|
||||
val kind=item.getString("kind");val data=item.getJSONObject("data");val minutes=data.optInt("reminderMinutes",-1)
|
||||
if(minutes<0||kind !in listOf("event","anniversary")||(kind=="anniversary"&&!SyncClient.connected(context)))return@runCatching null
|
||||
val first=if(kind=="event")maxOf(today.minusDays(2),LocalDate.parse(data.getString("date"))) else today.minusDays(2)
|
||||
val event=if(kind=="event")PlannerStore.eventRule(data) else null
|
||||
val annual=if(kind=="anniversary")Anniversaries.rule(data) else null
|
||||
(0L..400L).asSequence().map{first.plusDays(it)}.mapNotNull occurrence@{date->
|
||||
val occurs=if(event!=null)event.occurrenceOn(date)==date else annual!!.matches(date,if(annual.calendar=="LUNAR")LunarDates.day(context,date) else null)
|
||||
if(!occurs)return@occurrence null
|
||||
val time=if(kind=="anniversary"||data.getBoolean("allDay"))LocalTime.of(9,0) else LocalTime.parse(data.getString("startTime"))
|
||||
val at=date.atTime(time).atZone(zone).minusMinutes(minutes.toLong()).toInstant().toEpochMilli()
|
||||
if(at>after)Plan(item.getString("id"),date,at,data.getString("title")) else null
|
||||
}.firstOrNull()
|
||||
}.getOrNull()}.sortedBy{it.at}
|
||||
}
|
||||
private fun intent(context:Context,at:Long=0)=Intent(context,ReminderReceiver::class.java).setAction(ACTION).setData(Uri.parse("dutycalendar://reminder")).putExtra("at",at)
|
||||
private fun pending(context:Context,at:Long=0)=PendingIntent.getBroadcast(context,7202,intent(context,at),PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
|
||||
fun reschedule(context:Context){val app=context.applicationContext;executor.execute{runCatching{schedule(app)}}}
|
||||
@Synchronized private fun schedule(context:Context) {
|
||||
val alarm=context.getSystemService(AlarmManager::class.java);alarm.cancel(pending(context))
|
||||
val preferences=context.getSharedPreferences("reminders",0)
|
||||
if(!allowed(context)){preferences.edit().remove("at").apply();return}
|
||||
val next=plans(context,System.currentTimeMillis()).firstOrNull()
|
||||
if(next==null){preferences.edit().remove("at").apply();return}
|
||||
preferences.edit().putLong("at",next.at).commit()
|
||||
alarm.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP,next.at,pending(context,next.at))
|
||||
}
|
||||
@Synchronized fun receive(context:Context,intent:Intent) {
|
||||
if(intent.action==ACTION&&allowed(context)) {
|
||||
val at=intent.getLongExtra("at",0);val stored=context.getSharedPreferences("reminders",0).getLong("at",-1)
|
||||
if(at==stored&&at>0&&at<=System.currentTimeMillis()+1000) {
|
||||
val manager=context.getSystemService(NotificationManager::class.java)
|
||||
manager.createNotificationChannel(NotificationChannel("schedule","일정과 기념일",NotificationManager.IMPORTANCE_DEFAULT))
|
||||
for(plan in plans(context,at-1).filter{it.at<=System.currentTimeMillis()}) {
|
||||
val open=Intent(context,MainActivity::class.java).setData(Uri.parse("dutycalendar://date/${plan.date}")).putExtra("selectedDate",plan.date.toString())
|
||||
val tap=PendingIntent.getActivity(context,0,open,PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
|
||||
val notice=Notification.Builder(context,"schedule").setSmallIcon(R.drawable.ic_calendar).setContentTitle(plan.title)
|
||||
.setContentText("${plan.date} · 등록한 일정 알림").setContentIntent(tap).setAutoCancel(true).setVisibility(Notification.VISIBILITY_PRIVATE).build()
|
||||
manager.notify(plan.id,0,notice)
|
||||
}
|
||||
}
|
||||
}
|
||||
schedule(context)
|
||||
}
|
||||
}
|
||||
|
||||
class ReminderReceiver:BroadcastReceiver() {
|
||||
override fun onReceive(context:Context,intent:Intent) {
|
||||
val pending=goAsync()
|
||||
Thread{try{runCatching{Reminders.receive(context.applicationContext,intent)}}finally{pending.finish()}}.start()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package kr.co.itosm.dutycalendar
|
||||
|
||||
import java.time.LocalDate
|
||||
import java.time.YearMonth
|
||||
import java.time.temporal.ChronoUnit
|
||||
|
||||
/**
|
||||
* 근무의 표시 이름과 색상을 한곳에서 관리한다. 앱 달력과 홈 위젯은 같은 구분을 사용한다.
|
||||
* 좁은 날짜 칸에는 shortTitle을 쓰고 설정 화면과 접근성 설명에는 전체 이름을 쓴다.
|
||||
* 저장할 때는 표시 이름이 아닌 열거형 이름을 사용하므로 문구를 바꿔도 기존 근무표를 읽을 수 있다.
|
||||
*/
|
||||
enum class Shift(val title: String, val shortTitle: String, val color: Int, val pale: Int) {
|
||||
DUTY("당직", "당직", 0xFFAA4C2E.toInt(), 0xFFFAEADD.toInt()),
|
||||
OFF("비번", "비번", 0xFF64748B.toInt(), 0xFFEEF2F6.toInt()),
|
||||
REGULAR("일반근무", "일반", 0xFF365FAD.toInt(), 0xFFEAF0FC.toInt()),
|
||||
DAY("주간", "주간", 0xFFA75A14.toInt(), 0xFFFFF1DF.toInt()),
|
||||
EVENING("오후", "오후", 0xFFAD3D6E.toInt(), 0xFFFBEAF0.toInt()),
|
||||
NIGHT("야간", "야간", 0xFF79459D.toInt(), 0xFFF1EAF8.toInt()),
|
||||
REST("휴무", "휴무", 0xFF64748B.toInt(), 0xFFF0F3F5.toInt());
|
||||
|
||||
val working: Boolean get() = this != OFF && this != REST
|
||||
}
|
||||
|
||||
/**
|
||||
* anchor는 반복 순서의 첫째 날이다. pattern에 정해진 근무를 날짜 단위로 계속 반복한다.
|
||||
* 공휴일 여부는 근무 순서를 바꾸지 않는다. 공휴일 표시는 달력에서 별도로 덧붙인다.
|
||||
* 날짜 차이를 사용하므로 월말과 연말 및 윤년에도 주기가 끊기지 않는다.
|
||||
* 현재는 교대 시작 시각을 계산하지 않는다. 당직과 비번은 각각 한 날짜를 차지한다.
|
||||
*/
|
||||
data class Schedule(val anchor: LocalDate, val pattern: List<Shift>, val workWeek: Int = 6, val dutyAsWeekday: Boolean = false, val showLunar: Boolean = false, val offAsHoliday: Boolean = false) {
|
||||
init {
|
||||
require(pattern.size in 1..MAX_DAYS) { "반복 일수는 1일부터 ${MAX_DAYS}일까지 지정할 수 있습니다." }
|
||||
require(workWeek == 5 || workWeek == 6) { "주5일제 또는 주6일제를 선택해 주세요." }
|
||||
}
|
||||
fun shiftOn(date: LocalDate): Shift {
|
||||
// 기준일 이전 날짜도 같은 반복에 속한다. 음수 나머지를 그대로 쓰면 배열 범위를 벗어난다.
|
||||
val index = Math.floorMod(ChronoUnit.DAYS.between(anchor, date), pattern.size.toLong()).toInt()
|
||||
val planned = pattern[index]
|
||||
// 토요일 휴무는 해당 날짜의 표시와 근무 여부만 바꾼다. 다음 날의 반복 위치를 미루지 않는다.
|
||||
// 주5일제여도 당직은 유지한다. 기존 자료는 주6일제로 읽어 저장한 근무 순서를 보존한다.
|
||||
return if (workWeek == 5 && date.dayOfWeek.value == 6 && planned != Shift.DUTY) Shift.REST else planned
|
||||
}
|
||||
val saturdayColor: Int get() = if (workWeek == 5) 0xFFBD5163.toInt() else 0xFF365FAD.toInt()
|
||||
fun dateColor(date: LocalDate, holiday: Boolean = false): Int = when {
|
||||
// 당직일의 날짜 색만 평일로 바꾼다. 휴일 이름과 당직 순서는 원래 자료를 유지한다.
|
||||
dutyAsWeekday && shiftOn(date) == Shift.DUTY -> 0xFF1D2939.toInt()
|
||||
offAsHoliday && shiftOn(date) == Shift.OFF -> 0xFFBD5163.toInt()
|
||||
holiday || date.dayOfWeek.value == 7 -> 0xFFBD5163.toInt()
|
||||
date.dayOfWeek.value == 6 -> saturdayColor
|
||||
else -> 0xFF1D2939.toInt()
|
||||
}
|
||||
// 비번을 빨간색으로 볼지는 근무표의 표시 선택이다. 전역 근무 종류와 실제 휴무 계산은 바꾸지 않는다.
|
||||
fun shiftColor(date: LocalDate): Int = if (offAsHoliday && shiftOn(date) == Shift.OFF) 0xFFBD5163.toInt() else shiftOn(date).color
|
||||
fun shiftPale(date: LocalDate): Int = if (offAsHoliday && shiftOn(date) == Shift.OFF) 0xFFFBEAEC.toInt() else shiftOn(date).pale
|
||||
companion object {
|
||||
// 연 단위 주기까지 입력할 수 있다. 무제한 입력으로 편집 화면과 동기화 본문이 커지는 것은 막는다.
|
||||
const val MAX_DAYS = 366
|
||||
// 기본 순서는 당직 다음 비번이며 남은 날은 일반근무다. 저장 전 각 날을 자유롭게 바꿀 수 있다.
|
||||
fun preset(days: Int): List<Shift> {
|
||||
require(days in 1..MAX_DAYS)
|
||||
return List(days) { when (it) { 0 -> Shift.DUTY; 1 -> Shift.OFF; else -> Shift.REGULAR } }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 일요일부터 토요일까지 6주를 반환한다. 월마다 행 수를 바꾸지 않아 위젯 높이가 흔들리지 않는다.
|
||||
* LocalDate의 요일 값은 월요일이 1이고 일요일이 7이다. 나머지 연산으로 일요일을 0으로 맞춘다.
|
||||
* 앞뒤 달 날짜도 함께 반환한다. 화면에서만 흐리게 표시하고 근무 계산에는 실제 날짜를 사용한다.
|
||||
*/
|
||||
fun calendarDays(month: YearMonth): List<LocalDate> {
|
||||
val first = month.atDay(1)
|
||||
val start = first.minusDays((first.dayOfWeek.value % 7).toLong())
|
||||
return List(42) { start.plusDays(it.toLong()) }
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package kr.co.itosm.dutycalendar
|
||||
|
||||
import android.content.Context
|
||||
import java.time.LocalDate
|
||||
|
||||
/**
|
||||
* 기준일과 반복 순서를 앱 전용 저장소에 함께 보관한다. 앱 화면과 위젯이 같은 자료를 읽는다.
|
||||
* 표시 문구 대신 ISO 날짜와 근무 식별자를 저장해 휴대폰 언어나 문구 변경의 영향을 줄인다.
|
||||
* 웹 연결을 사용하면 같은 설정을 일정 저장소의 전송 대기 목록에도 남긴다.
|
||||
*/
|
||||
object ScheduleStore {
|
||||
private fun preferences(context: Context) = context.getSharedPreferences("schedule", Context.MODE_PRIVATE)
|
||||
// 설치 직후의 예시 근무표를 실제 설정으로 오해하지 않도록 기준일 저장 여부를 따로 확인한다.
|
||||
fun isConfigured(context: Context): Boolean = preferences(context).contains("anchor")
|
||||
fun load(context: Context): Schedule {
|
||||
val prefs = preferences(context)
|
||||
// 손상된 날짜나 알 수 없는 근무 값 때문에 달력 전체가 종료되지 않도록 기본값으로 복구한다.
|
||||
// 이 과정에서는 원래 저장 내용을 덮어쓰지 않는다. 새로 저장할 때만 설정을 변경한다.
|
||||
return runCatching {
|
||||
Schedule(
|
||||
LocalDate.parse(prefs.getString("anchor", LocalDate.now().toString())),
|
||||
prefs.getString("pattern", "DUTY,OFF")!!.split(",").map(Shift::valueOf),
|
||||
prefs.getInt("workWeek", 6),
|
||||
prefs.getBoolean("dutyAsWeekday", false),
|
||||
prefs.getBoolean("showLunar", false),
|
||||
prefs.getBoolean("offAsHoliday", false)
|
||||
)
|
||||
}.getOrElse { Schedule(LocalDate.now(), Schedule.preset(2)) }
|
||||
}
|
||||
/** 표시 선택만 먼저 저장해도 예시 근무표가 실제 근무표로 등록되지는 않게 한다.
|
||||
* 기초 설정이 있으면 최신 기준일과 순서를 그대로 복사해 옵션 세 항목만 갱신한다.
|
||||
* 따라서 옵션 창을 연 사이에 다른 기기에서 받은 근무표를 이전 값으로 되돌리지 않는다.
|
||||
*/
|
||||
fun saveDisplay(context: Context, dutyAsWeekday: Boolean, showLunar: Boolean, offAsHoliday: Boolean, fromSync: Boolean = false) {
|
||||
check(preferences(context).edit().putBoolean("dutyAsWeekday", dutyAsWeekday)
|
||||
.putBoolean("showLunar", showLunar).putBoolean("offAsHoliday", offAsHoliday).commit()) { "저장 공간을 확인해 주세요." }
|
||||
// 개인 표시 선택은 근무표와 별도 항목으로 저장한다. 회원은 근무표를 아직 만들지 않아도 복원할 수 있다.
|
||||
if (!fromSync && (isConfigured(context) || PlannerStore.calendarId(context).isNotBlank())) {
|
||||
PlannerStore.queuePreferences(context, load(context))
|
||||
SyncClient.sync(context)
|
||||
}
|
||||
DutyWidget.updateAll(context)
|
||||
}
|
||||
fun save(context: Context, schedule: Schedule, fromSync: Boolean = false) {
|
||||
// 한 편집 작업으로 기준일과 순서를 갱신한다. apply는 메모리에 먼저 반영하므로
|
||||
// 바로 아래에서 위젯을 다시 그릴 때도 새 근무표를 읽는다. 디스크 기록은 비동기로 진행된다.
|
||||
preferences(context).edit()
|
||||
.putString("anchor", schedule.anchor.toString())
|
||||
.putString("pattern", schedule.pattern.joinToString(",") { it.name })
|
||||
.putInt("workWeek", schedule.workWeek)
|
||||
.putBoolean("dutyAsWeekday", schedule.dutyAsWeekday)
|
||||
.putBoolean("showLunar", schedule.showLunar)
|
||||
.putBoolean("offAsHoliday", schedule.offAsHoliday)
|
||||
.apply()
|
||||
if (!fromSync) {
|
||||
PlannerStore.queueRotation(context, schedule)
|
||||
SyncClient.sync(context)
|
||||
}
|
||||
DutyWidget.updateAll(context)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
package kr.co.itosm.dutycalendar
|
||||
|
||||
import android.content.Context
|
||||
import android.text.Editable
|
||||
import android.text.InputType
|
||||
import android.text.TextWatcher
|
||||
import android.view.Gravity
|
||||
import android.view.View
|
||||
import android.widget.*
|
||||
import org.json.JSONArray
|
||||
|
||||
/**
|
||||
* 본인과 함께 볼 사람의 근무 편집을 같은 화면으로 처리한다.
|
||||
* 유형은 편집을 시작하는 예시다. 조 수만으로 사업장의 실제 근무 순서를 확정하지 않는다.
|
||||
* 숫자를 바꾸면 일당직은 당직·비번 뒤의 남은 날을 선택한 근무로 채운다.
|
||||
* 직접 설정에서는 기존 앞부분을 보존한다. 빈 값이나 범위를 벗어난 값은 저장할 수 없다.
|
||||
*/
|
||||
class ShiftPatternEditor(context: Context, initial: List<Shift>, initialWorkWeek: Int = 6) : LinearLayout(context) {
|
||||
private var draft = initial.toMutableList()
|
||||
private var updating = false
|
||||
private var generation = 0
|
||||
private val templates = JSONArray(context.assets.open("work-patterns.json").bufferedReader().use { it.readText() })
|
||||
private val mode = Spinner(context)
|
||||
private val countLabel = TextView(context)
|
||||
private val count = EditText(context)
|
||||
private val remainder = Spinner(context)
|
||||
private val remainderLabel = TextView(context)
|
||||
private val rows = LinearLayout(context)
|
||||
private val error = TextView(context)
|
||||
private val summary = TextView(context)
|
||||
private val workWeek = Spinner(context)
|
||||
private fun dp(value: Int) = (value * resources.displayMetrics.density).toInt()
|
||||
private fun caption(value: String) = TextView(context).apply { text = value; textSize = 14f; setPadding(0, dp(12), 0, dp(6)) }
|
||||
|
||||
init {
|
||||
orientation = VERTICAL
|
||||
addView(caption("토요일 근무제"))
|
||||
workWeek.adapter = ArrayAdapter(context, android.R.layout.simple_spinner_dropdown_item,
|
||||
listOf("주5일제 · 토요일 당직만 근무", "주6일제 · 토요일 기존 근무"))
|
||||
workWeek.contentDescription = "토요일 근무제"
|
||||
workWeek.setSelection(if (initialWorkWeek == 5) 0 else 1, false)
|
||||
addView(workWeek)
|
||||
addView(caption("주5일제는 토요일을 빨간색으로 표시하며 당직이 아니면 휴무입니다. 주6일제는 파란색으로 표시하고 원래 근무를 따릅니다."))
|
||||
addView(caption("근무 유형"))
|
||||
mode.adapter = ArrayAdapter(context, android.R.layout.simple_spinner_dropdown_item,
|
||||
listOf("직접 설정", "일당직 · 숫자로 입력") + (0 until templates.length()).map { templates.getJSONObject(it).getString("name") })
|
||||
mode.contentDescription = "근무 유형"
|
||||
addView(mode)
|
||||
countLabel.text = "반복 일수 (1~366일)"; countLabel.setPadding(0, dp(12), 0, dp(6)); addView(countLabel)
|
||||
count.inputType = InputType.TYPE_CLASS_NUMBER; count.setSingleLine(true); count.setText(initial.size.toString())
|
||||
count.contentDescription = "당직 숫자 또는 반복 일수"; addView(count)
|
||||
remainderLabel.text = "당직·비번 다음 남은 날"; addView(remainderLabel)
|
||||
remainder.adapter = ArrayAdapter(context, android.R.layout.simple_spinner_dropdown_item, listOf("일반근무", "비번", "휴무"))
|
||||
remainder.contentDescription = "일당직 남은 날 근무"; addView(remainder)
|
||||
remainder.visibility = GONE; remainderLabel.visibility = GONE
|
||||
error.setTextColor(0xFFAD3D6E.toInt()); addView(error)
|
||||
summary.textSize = 12f; summary.setPadding(0, dp(8), 0, dp(8)); addView(summary)
|
||||
addView(caption("매일의 근무 · 선택 후 수정 가능"))
|
||||
rows.orientation = VERTICAL; addView(rows)
|
||||
addView(caption("유형은 예시입니다. 실제 근무 순서와 첫째 날을 확인해 주세요. 비번과 휴무는 따로 표시합니다."))
|
||||
draw()
|
||||
mode.onItemSelectedListener = listener { position ->
|
||||
val duty = position == 1
|
||||
remainder.visibility = if (duty) VISIBLE else GONE
|
||||
remainderLabel.visibility = remainder.visibility
|
||||
countLabel.text = if (duty) "몇 당직인가요? (2~366)" else "반복 일수 (1~366일)"
|
||||
if (position >= 2) {
|
||||
val values = templates.getJSONObject(position - 2).getJSONArray("pattern")
|
||||
draft = MutableList(values.length()) { Shift.valueOf(values.getString(it)) }
|
||||
updating = true; count.setText(draft.size.toString()); updating = false; error.text = ""; draw()
|
||||
} else if (duty) {
|
||||
if ((count.text.toString().toIntOrNull() ?: 0) < 2) count.setText("2")
|
||||
resize()
|
||||
}
|
||||
}
|
||||
count.addTextChangedListener(object : TextWatcher {
|
||||
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit
|
||||
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { if (!updating) resize() }
|
||||
override fun afterTextChanged(s: Editable?) = Unit
|
||||
})
|
||||
remainder.onItemSelectedListener = listener { if (mode.selectedItemPosition == 1 && !updating) resize() }
|
||||
}
|
||||
private fun listener(selected: (Int) -> Unit) = object : AdapterView.OnItemSelectedListener {
|
||||
override fun onNothingSelected(parent: AdapterView<*>?) = Unit
|
||||
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) = selected(position)
|
||||
}
|
||||
private fun resize() {
|
||||
val size = count.text.toString().toIntOrNull()
|
||||
val duty = mode.selectedItemPosition == 1
|
||||
val minimum = if (duty) 2 else 1
|
||||
if (size == null || size !in minimum..Schedule.MAX_DAYS) {
|
||||
error.text = "${minimum}~${Schedule.MAX_DAYS} 사이의 숫자를 입력해 주세요."; return
|
||||
}
|
||||
error.text = ""
|
||||
draft = if (duty) Schedule.preset(size).mapIndexed { index, shift ->
|
||||
if (index < 2) shift else listOf(Shift.REGULAR, Shift.OFF, Shift.REST)[remainder.selectedItemPosition.coerceAtLeast(0)]
|
||||
}.toMutableList() else MutableList(size) { draft.getOrElse(it) { Shift.REGULAR } }
|
||||
draw()
|
||||
}
|
||||
private fun draw() {
|
||||
val currentGeneration = ++generation
|
||||
rows.removeAllViews()
|
||||
updateSummary()
|
||||
draft.forEachIndexed { index, shift ->
|
||||
val line = LinearLayout(context)
|
||||
line.addView(TextView(context).apply { text = "${index + 1}일째"; gravity = Gravity.CENTER_VERTICAL }, LayoutParams(dp(70), dp(48)))
|
||||
line.addView(Spinner(context).apply {
|
||||
adapter = ArrayAdapter(context, android.R.layout.simple_spinner_dropdown_item, Shift.entries.map { it.title })
|
||||
setSelection(shift.ordinal, false); contentDescription = "${index + 1}일째 근무 종류"
|
||||
// 다시 그린 이전 행의 지연 선택 알림이 새 목록을 덮어쓰지 않도록 세대를 확인한다.
|
||||
onItemSelectedListener = listener { position ->
|
||||
if (generation == currentGeneration && index < draft.size) {
|
||||
draft[index] = Shift.entries[position]
|
||||
updateSummary()
|
||||
}
|
||||
}
|
||||
}, LayoutParams(0, dp(48), 1f))
|
||||
rows.addView(line)
|
||||
}
|
||||
}
|
||||
private fun updateSummary() {
|
||||
summary.text = draft.take(16).joinToString(" → ") { it.title } + if (draft.size > 16) " … (${draft.size}일 반복)" else ""
|
||||
}
|
||||
fun pattern(): List<Shift> {
|
||||
val minimum = if (mode.selectedItemPosition == 1) 2 else 1
|
||||
val size = count.text.toString().toIntOrNull()
|
||||
require(size != null && size in minimum..Schedule.MAX_DAYS && size == draft.size) { "반복 일수를 확인해 주세요. ${minimum}~${Schedule.MAX_DAYS} 사이로 입력해 주세요." }
|
||||
return draft.toList()
|
||||
}
|
||||
fun workWeek(): Int = if (workWeek.selectedItemPosition == 0) 5 else 6
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
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<Boolean> { 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<Boolean> { 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())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package kr.co.itosm.dutycalendar
|
||||
|
||||
import android.app.Activity
|
||||
import android.app.AlertDialog
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import org.json.JSONObject
|
||||
import java.lang.ref.WeakReference
|
||||
import java.net.URL
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.util.concurrent.Executors
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
import javax.net.ssl.HttpsURLConnection
|
||||
|
||||
/**
|
||||
* 홈페이지에 공개된 버전 정보를 읽고 새 앱이 있으면 설치 파일을 받을지 묻는다.
|
||||
* 회원 인증값과 개인 자료를 보내지 않는다. 동의하면 앱 안에서 내려받아 검증한다. 적용과 필요한 사용자 확인은 설치 관리자가 담당한다.
|
||||
* 창을 띄울 수 없는 상태에서는 공개 정보만 보관했다가 다음 실행 때 다시 확인한다.
|
||||
*/
|
||||
object UpdateChecker {
|
||||
private val executor = Executors.newSingleThreadExecutor()
|
||||
private val checking = AtomicBoolean(false)
|
||||
private var showing = false
|
||||
fun check(activity: Activity, force: Boolean = false, fresh: Boolean = false) {
|
||||
if (AppUpdate.phase in listOf("downloading", "installing")) {
|
||||
if (force) AppUpdate.pending(activity)?.let { activity.startActivity(Intent(activity, AppUpdateActivity::class.java).putExtra("release", it.json().toString())) }
|
||||
return
|
||||
}
|
||||
val app = activity.applicationContext
|
||||
val prefs = app.getSharedPreferences("app_update", Context.MODE_PRIVATE)
|
||||
val cached = runCatching { JSONObject(prefs.getString("release", "")!!) }.getOrNull()
|
||||
if (!force) cached?.let { prompt(activity, it) }
|
||||
if ((!force && !fresh && !UpdatePolicy.needsCheck(prefs.getLong("checkedAt", 0), System.currentTimeMillis())) || !checking.compareAndSet(false, true)) return
|
||||
val reference = WeakReference(activity)
|
||||
executor.execute {
|
||||
try {
|
||||
val connection = URL(SyncClient.WEB_URL + "api/version").openConnection() as HttpsURLConnection
|
||||
val result = try {
|
||||
connection.connectTimeout = 8000; connection.readTimeout = 8000
|
||||
require(connection.responseCode == 200)
|
||||
val bytes = connection.inputStream.use { input ->
|
||||
val result = ByteArrayOutputStream()
|
||||
val buffer = ByteArray(2048)
|
||||
while (true) {
|
||||
val read = input.read(buffer)
|
||||
if (read < 0) break
|
||||
require(result.size() + read <= 16_384)
|
||||
result.write(buffer, 0, read)
|
||||
}
|
||||
result.toByteArray()
|
||||
}
|
||||
JSONObject(bytes.toString(Charsets.UTF_8)).also {
|
||||
require(it.getLong("appVersionCode") > 0 && it.getString("appVersion").length <= 40)
|
||||
}
|
||||
} finally { connection.disconnect() }
|
||||
val holidayRevision = result.optString("holidayRevision")
|
||||
if (holidayRevision.isNotBlank() && holidayRevision != Holidays.revision(app)) {
|
||||
Holidays.refresh(app, force = true, changedOnly = true) { reference.get()?.let { screen -> screen.runOnUiThread { if (screen is MainActivity && !screen.isDestroyed) screen.render() } } }
|
||||
}
|
||||
prefs.edit().putString("release", result.toString()).putLong("checkedAt", System.currentTimeMillis()).apply()
|
||||
reference.get()?.let { screen -> screen.runOnUiThread { if (force) prefs.edit().remove("deferred").remove("deferredUntil").apply(); prompt(screen, result); if (force && result.optLong("appVersionCode") <= AppUpdate.installed(app)) android.widget.Toast.makeText(screen, "현재 최신 버전입니다.", android.widget.Toast.LENGTH_SHORT).show() } }
|
||||
} catch (_: Exception) {
|
||||
// 업데이트 확인 실패가 달력 사용을 막지 않는다. 직접 확인했을 때는 실패를 분명히 알린다.
|
||||
if (force) reference.get()?.let { screen -> screen.runOnUiThread { android.widget.Toast.makeText(screen, "업데이트 정보를 확인하지 못했습니다. 연결 후 다시 시도해 주세요.", android.widget.Toast.LENGTH_LONG).show() } }
|
||||
} finally { checking.set(false) }
|
||||
}
|
||||
}
|
||||
private fun prompt(activity: Activity, release: JSONObject) {
|
||||
if (showing || activity.isFinishing || activity.isDestroyed || !activity.hasWindowFocus()) return
|
||||
val prefs = activity.getSharedPreferences("app_update", Context.MODE_PRIVATE)
|
||||
@Suppress("DEPRECATION")
|
||||
val info = activity.packageManager.getPackageInfo(activity.packageName, 0)
|
||||
@Suppress("DEPRECATION")
|
||||
val installed = if (android.os.Build.VERSION.SDK_INT >= 28) info.longVersionCode else info.versionCode.toLong()
|
||||
val remote = release.optLong("appVersionCode")
|
||||
if (!UpdatePolicy.shouldPrompt(remote, installed, prefs.getLong("deferred", 0), prefs.getLong("deferredUntil", 0), System.currentTimeMillis())) return
|
||||
fun later() { prefs.edit().putLong("deferred", remote).putLong("deferredUntil", System.currentTimeMillis() + UpdatePolicy.LATER_MS).apply() }
|
||||
val notes = release.optJSONArray("notes")?.let { list -> (0 until minOf(list.length(), 8)).joinToString("\n") { list.optString(it).take(200) } }.orEmpty()
|
||||
showing = true
|
||||
AlertDialog.Builder(activity).setTitle("새 버전 ${release.optString("appVersion")} 업데이트")
|
||||
.setMessage("새로운 당직근무이 준비됐습니다. 업데이트할까요?\n\n$notes\n\n동의하면 새 파일을 자동으로 내려받아 적용합니다. 처음에는 앱 설치 허용이 필요할 수 있습니다. 기기에 따라 설치 확인창이 표시됩니다. 기존 일정과 설정은 유지합니다.")
|
||||
.setPositiveButton("업데이트") { _, _ ->
|
||||
runCatching {
|
||||
val wanted = AppUpdate.parse(release)
|
||||
activity.startActivity(Intent(activity, AppUpdateActivity::class.java).putExtra("release", wanted.json().toString()))
|
||||
}.onFailure { android.widget.Toast.makeText(activity, "배포 정보를 확인하지 못했습니다. 업데이트 확인을 다시 눌러 주세요.", android.widget.Toast.LENGTH_LONG).show() }
|
||||
}.setNegativeButton("나중에") { _, _ -> later() }
|
||||
.setOnCancelListener { later() }.setOnDismissListener { showing = false }.show()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package kr.co.itosm.dutycalendar
|
||||
|
||||
/** 일정 갱신과 별개로 작은 버전 정보만 확인한다. 나중에 보기를 선택한 동일 버전은 하루 동안 다시 묻지 않는다. */
|
||||
object UpdatePolicy {
|
||||
const val CHECK_MS = 15L * 60 * 1000
|
||||
const val LATER_MS = 24L * 60 * 60 * 1000
|
||||
fun needsCheck(last: Long, now: Long) = last <= 0L || now < last || now - last >= CHECK_MS
|
||||
fun shouldPrompt(remote: Long, installed: Long, deferred: Long, until: Long, now: Long) =
|
||||
remote > installed && (remote != deferred || now >= until)
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package kr.co.itosm.dutycalendar
|
||||
|
||||
import android.app.Activity
|
||||
import android.app.AlertDialog
|
||||
import android.appwidget.AppWidgetManager
|
||||
import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import android.graphics.Color
|
||||
import android.view.View
|
||||
import android.widget.*
|
||||
import org.json.JSONObject
|
||||
|
||||
/** 위젯 모양은 휴대폰의 배경과 배치 크기에 종속되므로 회원 공통 설정과 분리한다.
|
||||
* 기본값은 새 위젯에 적용한다. 개별 위젯은 별도 값을 가질 수 있으며 전체 적용을 고르면 기존 개별 값도 함께 바꾼다.
|
||||
* 투명도는 배경에만 적용한다. 글자까지 투명하게 만들면 낮은 값에서 날짜를 읽을 수 없기 때문이다.
|
||||
*/
|
||||
data class WidgetStyle(
|
||||
val transparency:Int=0, val dark:Boolean=false, val scale:Int=100, val detail:String="AUTO",
|
||||
val lunar:Boolean=true, val holidays:Boolean=true, val people:Boolean=true,
|
||||
val anniversaries:Boolean=true, val eventMark:Boolean=true, val today:Boolean=true
|
||||
) {
|
||||
init { require(transparency in 0..100 && scale in listOf(80,100,120) && detail in listOf("AUTO","COMPACT","FULL")) }
|
||||
val background:Int get()=(((255*(100-transparency)+50)/100) shl 24) or (if(dark)0x182333 else 0xFFFEFA)
|
||||
val ink:Int get()=if(dark)0xFFF4F6FA.toInt() else 0xFF1D2939.toInt()
|
||||
val muted:Int get()=if(dark)0xFFBECBDD.toInt() else 0xFF64748B.toInt()
|
||||
fun compact(height:Int)=detail=="COMPACT"||(detail=="AUTO"&&height<360)
|
||||
fun color(original:Int):Int {
|
||||
if(!dark)return original
|
||||
if(original==0xFF1D2939.toInt()||original==0xFF26364D.toInt())return ink
|
||||
fun bright(value:Int)=value+(255-value)*38/100
|
||||
return Color.rgb(bright(Color.red(original)),bright(Color.green(original)),bright(Color.blue(original)))
|
||||
}
|
||||
fun json()=JSONObject().put("transparency",transparency).put("dark",dark).put("scale",scale).put("detail",detail)
|
||||
.put("lunar",lunar).put("holidays",holidays).put("people",people).put("anniversaries",anniversaries).put("eventMark",eventMark).put("today",today)
|
||||
companion object {
|
||||
fun parse(value:String)=JSONObject(value).let{WidgetStyle(it.optInt("transparency",0),it.optBoolean("dark",false),it.optInt("scale",100),it.optString("detail","AUTO"),it.optBoolean("lunar",true),it.optBoolean("holidays",true),it.optBoolean("people",true),it.optBoolean("anniversaries",true),it.optBoolean("eventMark",true),it.optBoolean("today",true))}
|
||||
fun load(context:Context,id:Int?=null):WidgetStyle {
|
||||
val prefs=context.getSharedPreferences("widget_style",0)
|
||||
return runCatching{parse(prefs.getString(if(id!=null&&prefs.contains("style_$id"))"style_$id" else "default","{}")!!)}.getOrDefault(WidgetStyle())
|
||||
}
|
||||
fun save(context:Context,id:Int?,style:WidgetStyle) {
|
||||
val prefs=context.getSharedPreferences("widget_style",0);val edit=prefs.edit()
|
||||
if(id==null){prefs.all.keys.filter{it.startsWith("style_")}.forEach{edit.remove(it)};edit.putString("default",style.json().toString())}
|
||||
else edit.putString("style_$id",style.json().toString())
|
||||
check(edit.commit()){ "위젯 설정을 저장하지 못했습니다. 저장 공간을 확인해 주세요." }
|
||||
DutyWidget.updateAll(context)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
object WidgetStyleDialog {
|
||||
fun show(activity:Activity,id:Int?=null) {
|
||||
val ids=AppWidgetManager.getInstance(activity).getAppWidgetIds(ComponentName(activity,DutyWidget::class.java))
|
||||
if(id!=null){if(id in ids)edit(activity,id);return}
|
||||
if(ids.isEmpty()){edit(activity,null);return}
|
||||
AlertDialog.Builder(activity).setTitle("꾸밀 위젯 선택")
|
||||
.setItems((listOf("모든 위젯과 새 위젯의 기본값")+ids.mapIndexed{index,_->"위젯 ${index+1}"}).toTypedArray()){_,index->edit(activity,if(index==0)null else ids[index-1])}
|
||||
.setNegativeButton("닫기",null).show()
|
||||
}
|
||||
private fun edit(activity:Activity,id:Int?) {
|
||||
val original=WidgetStyle.load(activity,id)
|
||||
fun dp(value:Int)=(value*activity.resources.displayMetrics.density).toInt()
|
||||
val form=LinearLayout(activity).apply{orientation=LinearLayout.VERTICAL;setPadding(dp(20),dp(8),dp(20),dp(16))}
|
||||
fun label(value:String)=TextView(activity).apply{text=value;textSize=13f;setPadding(0,dp(12),0,dp(5));form.addView(this)}
|
||||
fun spinner(title:String,values:List<String>,choice:Int):Spinner {label(title);return Spinner(activity).apply{adapter=ArrayAdapter(activity,android.R.layout.simple_spinner_dropdown_item,values);setSelection(choice);contentDescription=title;form.addView(this)}}
|
||||
label(if(id==null)"이 휴대폰의 모든 위젯에 적용합니다. 회원의 근무표와 다른 기기의 설정은 바뀌지 않습니다." else "선택한 위젯 하나에만 적용합니다. 다른 위젯의 모양은 유지합니다.")
|
||||
// 완전히 투명한 배경에서도 밝은 글자를 확인할 수 있도록 중간 명도의 미리보기 바탕을 둔다.
|
||||
val previewFrame=FrameLayout(activity).apply{setBackgroundColor(0xFF69798A.toInt());form.addView(this,LinearLayout.LayoutParams(-1,dp(86)))}
|
||||
val preview=TextView(activity).apply{text="2026년 11월\n20 당직 21 비번 22 일반";setPadding(dp(12),dp(12),dp(12),dp(12));previewFrame.addView(this,FrameLayout.LayoutParams(-1,-1))}
|
||||
val opacityLabel=label("배경 투명도 ${original.transparency}%")
|
||||
val opacity=SeekBar(activity).apply{max=100;progress=original.transparency;contentDescription="배경 투명도";form.addView(this)}
|
||||
label("0%는 불투명 배경이며 100%는 배경 없이 글자만 표시합니다.")
|
||||
val theme=spinner("배경과 글자 색상",listOf("밝은 배경 · 어두운 글자","어두운 배경 · 밝은 글자"),if(original.dark)1 else 0)
|
||||
val size=spinner("글자 크기",listOf("작게 · 80%","기본 · 100%","크게 · 120%"),listOf(80,100,120).indexOf(original.scale))
|
||||
val details=spinner("내용 배치",listOf("자동 · 위젯 크기에 맞춤","간단히 · 날짜와 근무","자세히 · 추가 정보 표시"),listOf("AUTO","COMPACT","FULL").indexOf(original.detail))
|
||||
label("위젯 전체 크기는 홈 화면에서 위젯을 길게 누른 뒤 테두리를 끌어 조절합니다. 작은 위젯은 간단한 배치가 읽기 좋습니다.")
|
||||
fun choice(title:String,value:Boolean)=CheckBox(activity).apply{text=title;isChecked=value;textSize=14f;minHeight=dp(42);form.addView(this)}
|
||||
val lunar=choice("음력 표시 · 앱의 음력 옵션을 따름",original.lunar)
|
||||
val holidays=choice("공휴일 이름 표시",original.holidays)
|
||||
val people=choice("함께 근무하는 사람 표시",original.people)
|
||||
val anniversaries=choice("기념일 이름 표시",original.anniversaries)
|
||||
val marks=choice("일정과 기념일의 + 표시",original.eventMark)
|
||||
val today=choice("오늘 날짜 배경 강조",original.today)
|
||||
label("간단한 배치는 추가 글줄을 숨깁니다. 날짜를 누르면 앱에서 전체 내용을 볼 수 있습니다. 투명한 배경에는 바탕화면과 대비되는 글자 색상을 선택하세요.")
|
||||
fun value()=WidgetStyle(opacity.progress,theme.selectedItemPosition==1,listOf(80,100,120)[size.selectedItemPosition],listOf("AUTO","COMPACT","FULL")[details.selectedItemPosition],lunar.isChecked,holidays.isChecked,people.isChecked,anniversaries.isChecked,marks.isChecked,today.isChecked)
|
||||
fun updatePreview(){val style=value();preview.setBackgroundColor(style.background);preview.setTextColor(style.ink);preview.textSize=16*style.scale/100f;opacityLabel.text="배경 투명도 ${style.transparency}%"}
|
||||
val listener=object:AdapterView.OnItemSelectedListener{override fun onNothingSelected(parent:AdapterView<*>?){};override fun onItemSelected(parent:AdapterView<*>?,view:View?,position:Int,rowId:Long){updatePreview()}}
|
||||
theme.onItemSelectedListener=listener;size.onItemSelectedListener=listener
|
||||
opacity.setOnSeekBarChangeListener(object:SeekBar.OnSeekBarChangeListener{override fun onStartTrackingTouch(bar:SeekBar){};override fun onStopTrackingTouch(bar:SeekBar){};override fun onProgressChanged(bar:SeekBar,progress:Int,fromUser:Boolean){updatePreview()}})
|
||||
val dialog=AlertDialog.Builder(activity).setTitle("위젯 꾸미기").setView(ScrollView(activity).apply{addView(form)})
|
||||
.setNegativeButton("취소",null).setNeutralButton("기본값",null).setPositiveButton("저장",null).create()
|
||||
dialog.setOnShowListener{
|
||||
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener{runCatching{WidgetStyle.save(activity,id,value())}.onSuccess{dialog.dismiss();Toast.makeText(activity,"위젯 모양을 저장했습니다.",Toast.LENGTH_SHORT).show()}.onFailure{Toast.makeText(activity,it.message,Toast.LENGTH_LONG).show()}}
|
||||
dialog.getButton(AlertDialog.BUTTON_NEUTRAL).setOnClickListener{opacity.progress=0;theme.setSelection(0);size.setSelection(1);details.setSelection(0);listOf(lunar,holidays,people,anniversaries,marks,today).forEach{it.isChecked=true};updatePreview()}
|
||||
}
|
||||
dialog.show();updatePreview()
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user