위젯 꾸미기 중복 실행 수정과 달력 처리 및 배포 보안 보완

위젯과 알림에서 기존 MainActivity를 재사용하고 전달한 날짜와 꾸미기 요청을 한 번만 처리한다. 꾸미기 창은 중복 생성하지 않으며 화면 종료 때 닫는다. 첫 실행의 화면 중복 그리기도 제거했다.

CalendarSnapshot으로 화면별 원본과 전송 대기를 한 번 읽고 반복 규칙을 재사용한다. 개별 위젯 저장과 날짜 변경 수신자의 갱신 범위를 줄였다. 기본 달력 권한 승인 후 설정을 이어서 열고 기존 하루 예약을 유지한다.

다른 기기에서 복원한 달력 번호로 자동 쓰기가 시작되지 않도록 기기 표식을 검사한다. 기기 종속 설정은 백업과 기기 이전에서 제외한다. 개인 근무와 일정은 보존한다. 배포 APK는 기존 인증서를 사용하는 release 빌드로 바꾸고 디버깅을 껐다. 평문 통신 금지를 명시했다.

주요 파일: AppNavigation과 MainActivity 및 WidgetStyle. CalendarSnapshot과 PlannerStore 및 People와 위젯 렌더러. CalendarMirror와 백업 규칙 및 Manifest와 Gradle 설정. 관련 검사와 사용법 및 Android 제작 매뉴얼과 배포 절차.

앱 단위 42개와 서버 74개 및 배포 빌드와 정적 검사 통과. 오류 0개와 경고 86개. 실제 release APK에서 화면 재사용과 편집 창 단일 유지 및 날짜 이동과 잘못된 입력 거부를 확인했다. 네 위젯 크기와 주 시작 및 글자 배율과 기본 달력의 등록·수정·중복 방지·삭제 및 복원 보호 검사를 통과했다. 200개 일정의 42일 조회 결과가 같았으며 같은 가상 기기의 자료 처리 경로는 113ms에서 6ms로 측정됐다. 전체 앱 성능을 뜻하는 수치는 아니다. 공개 소스 ZIP의 release 빌드도 별도 폴더에서 통과했다.

0.13.2 설치 번호 19 운영 반영. DB 구조 변경과 자료 이전 없음. 기존 회원과 일정 및 소속과 월요일 시작 설정 및 다른 서비스와 원격 세션 보존. 변경 전 소스와 DB는 비공개 20261121-widget-fix 백업에 보관했다. APK와 전체 소스 및 변경 안내는 당직근무 포럼에 게시한다.

실물 휴대폰과 제조사별 홈 화면 및 장시간 절전은 미확인이다. 기존 인증서를 유지하며 스토어용 서명 관리 체계는 후속 범위다.
This commit is contained in:
블리어 committed 2026-11-21 01:23:33 +00:00
1 parent 1fc9243c63
commit 2b67afd751
27 files changed
+413 -73

No files matched your search

+13 -2
View File
@@ -6,14 +6,25 @@ android {
namespace = "kr.co.itosm.dutycalendar"
compileSdk = 36
buildToolsVersion = "36.0.0"
// 배포본 자체의 동작도 검사할 수 있도록 검사 대상 종류를 명시적으로 고른다.
testBuildType = providers.gradleProperty("testBuildType").getOrElse("debug")
defaultConfig {
applicationId = "kr.co.itosm.dutycalendar"
minSdk = 26
targetSdk = 36
versionCode = 18
versionName = "0.13.1"
versionCode = 19
versionName = "0.13.2"
testInstrumentationRunner = "kr.co.itosm.dutycalendar.StorageSyncCheck"
}
buildTypes {
getByName("release") {
// 기존 설치본 위에 업데이트할 수 있도록 같은 인증서를 사용한다. 빌드 종류와
// 서명 인증서는 별개다. 배포본은 디버깅을 끄며 서명 키 파일은 소스에 포함하지 않는다.
signingConfig = signingConfigs.getByName("debug")
isDebuggable = false
isMinifyEnabled = false
}
}
// 빌드 도구는 JDK 21로 실행하지만 앱의 Java와 Kotlin 바이트코드 대상은 17로 통일한다.
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
@@ -22,6 +22,21 @@ object CalendarBridgeCheck {
var calendar:Long?=null;var passed=false;var stage="달력 만들기"
try{
check(CalendarMirror.allowed(app))
stage="기기 복원과 표식 검사"
val mirror=CalendarMirror.prefs(app)
mirror.edit().putBoolean("enabled",true).putString("owner",UUID.randomUUID().toString()).commit()
check(!CalendarMirror.enabled(app)){"다른 기기의 자동 반영 선택을 허용했습니다."}
val restored=object:android.content.ContextWrapper(app){override fun getNoBackupFilesDir()=java.io.File(app.cacheDir,"restore-check-"+UUID.randomUUID())}
check(!CalendarMirror.enabled(restored)){"기기 표식 없이 자동 반영을 허용했습니다."}
mirror.edit().putBoolean("enabled",false).commit()
check(!android.security.NetworkSecurityPolicy.getInstance().isCleartextTrafficPermitted)
val expected=setOf("calendar_mirror.xml","widget.xml","widget_style.xml","web_sync.xml","app_update.xml")
for(resource in listOf(R.xml.backup_rules,R.xml.data_extraction_rules)) {
val seen=mutableListOf<String>();val parser=app.resources.getXml(resource)
parser.use { while(it.eventType!=org.xmlpull.v1.XmlPullParser.END_DOCUMENT){if(it.eventType==org.xmlpull.v1.XmlPullParser.START_TAG&&it.name=="exclude")seen.add(it.getAttributeValue(null,"path"));it.next()} }
check(seen.toSet()==expected)
if(resource==R.xml.data_extraction_rules)check(seen.size==expected.size*2)
}
val account="duty-qa-"+UUID.randomUUID();val uri=CalendarContract.Calendars.CONTENT_URI.buildUpon().appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER,"true").appendQueryParameter("account_name",account).appendQueryParameter("account_type",CalendarContract.ACCOUNT_TYPE_LOCAL).build()
calendar=ContentUris.parseId(checkNotNull(app.contentResolver.insert(uri,ContentValues().apply{put("account_name",account);put("account_type",CalendarContract.ACCOUNT_TYPE_LOCAL);put("name",account);put("calendar_displayName","달력 연동 검증");put("calendar_color",0xFF365FAD.toInt());put("calendar_access_level",700);put("ownerAccount",account);put("visible",1);put("sync_events",1)})))
val calendarId=calendar
@@ -45,6 +60,6 @@ object CalendarBridgeCheck {
original.forEach{(name,values)->val editor=app.getSharedPreferences(name,0).edit().clear();values.forEach{(key,value)->when(value){is String->editor.putString(key,value);is Boolean->editor.putBoolean(key,value);is Int->editor.putInt(key,value);is Long->editor.putLong(key,value);is Float->editor.putFloat(key,value)}};editor.commit()}
DutyWidget.updateAll(app)
}
test.finish(if(passed)Activity.RESULT_OK else Activity.RESULT_CANCELED,Bundle().apply{putString("stream",if(passed)"기본 달력 등록·변경·중복 방지·삭제 범위 검사 통과. 검증 달력 정리 완료." else "달력 검사 실패: $stage")})
test.finish(if(passed)Activity.RESULT_OK else Activity.RESULT_CANCELED,Bundle().apply{putString("stream",if(passed)"기기 표식 불일치·복원 시 자동 쓰기 차단과 백업 제외 및 평문 통신 차단 확인. 기본 달력 등록·변경·중복 방지·삭제 범위 검사 통과. 검증 달력 정리 완료." else "달력 검사 실패: $stage")})
}
}
@@ -0,0 +1,40 @@
package kr.co.itosm.dutycalendar
import android.content.Context
import org.json.JSONArray
import org.json.JSONObject
import java.time.LocalDate
import java.util.UUID
/** 표시용 자료 묶음의 결과와 회원 자료 숨김을 검사한다. 시간 측정은 같은 기기의 참고값이며 절대 성능 기준으로 쓰지 않는다. */
object SnapshotCheck {
fun run(context:Context):String {
check(!SyncClient.connected(context)&&!CalendarMirror.enabled(context))
val prefs=context.getSharedPreferences("planner",0);val original=prefs.getString("document",null)
val first=LocalDate.of(2026,11,1)
fun item(kind:String,data:JSONObject)=JSONObject().put("id",UUID.randomUUID().toString()).put("kind",kind).put("deleted",false).put("data",data)
val events=(0 until 200).map{index->item("event",JSONObject().put("title","검증 $index").put("date",first.plusDays((index%7).toLong()).toString()).put("endDate",first.plusDays((index%7).toLong()).toString()).put("allDay",false).put("startTime","09:00").put("endTime","10:00").put("repeat","WEEKLY").put("repeatUntil","").put("notes","").put("category","WORK"))}
val name=item("name_rule",JSONObject().put("name","평일 이름").put("mode","WEEKLY").put("anchor","2026-01-01").put("interval",1).put("weekdays",JSONArray(listOf(1,2,3,4,5))).put("enabled",true).put("personId","").put("color","BLUE"))
val annual=item("anniversary",JSONObject().put("title","개인 기념일").put("calendar","SOLAR").put("month",11).put("day",23).put("leapMonth",false))
val items=events+name+annual
try {
val document=JSONObject().put("state",JSONObject().put("items",JSONArray(items))).put("pending",JSONArray()).put("conflicts",JSONArray())
check(prefs.edit().putString("document",document.toString()).commit())
val started=System.nanoTime()
val legacy=(0L..41L).map{date->PlannerStore.eventsOn(context,first.plusDays(date)).map{it.getString("id")}}
val legacyMs=(System.nanoTime()-started)/1_000_000
val snapshotStart=System.nanoTime();val snapshot=CalendarSnapshot.load(context)
val actual=(0L..41L).map{date->snapshot.eventsOn(first.plusDays(date)).map{it.getString("id")}}
val snapshotMs=(System.nanoTime()-snapshotStart)/1_000_000
check(legacy==actual){"최적화 전후 일정 결과 불일치"}
val day=LocalDate.of(2026,11,23);val schedule=Schedule(first,listOf(Shift.REGULAR))
check(snapshot.anniversariesOn(day).isEmpty()&&snapshot.workNames(day,schedule).isEmpty())
val member=CalendarSnapshot(context,items,null,true)
check(member.anniversariesOn(day).single().getString("id")==annual.getString("id"))
check(member.workNames(day,schedule).single().name=="평일 이름")
return "일정 200개·42일 결과 일치와 회원 전용 자료 숨김 확인. 같은 기기 측정: 반복 읽기 ${legacyMs}ms / 한 번 읽기 ${snapshotMs}ms."
} finally {
val editor=prefs.edit();if(original==null)editor.remove("document") else editor.putString("document",original);check(editor.commit())
}
}
}
@@ -17,12 +17,13 @@ import java.util.concurrent.TimeUnit
* 계정 정보와 인증값은 결과에 출력하지 않는다. 배포 APK에는 이 검사 코드가 들어가지 않는다.
*/
class StorageSyncCheck : Instrumentation() {
private var widgetEntryCheck = false
private var calendarBridgeCheck = false
private var updateCheck = false
private var personalCheck = false
private var outageCheck = false
private var widgetCheck = false
override fun onCreate(arguments: Bundle?) { super.onCreate(arguments); calendarBridgeCheck = arguments?.getString("calendarBridgeCheck") == "true"; widgetCheck = arguments?.getString("widgetCheck") == "true"; outageCheck = arguments?.getString("outageCheck") == "true"; personalCheck = arguments?.getString("personalCheck") == "true"; updateCheck = arguments?.getString("updateCheck") == "true"; start() }
override fun onCreate(arguments: Bundle?) { super.onCreate(arguments); widgetEntryCheck=arguments?.getString("widgetEntryCheck")=="true"; calendarBridgeCheck = arguments?.getString("calendarBridgeCheck") == "true"; widgetCheck = arguments?.getString("widgetCheck") == "true"; outageCheck = arguments?.getString("outageCheck") == "true"; personalCheck = arguments?.getString("personalCheck") == "true"; updateCheck = arguments?.getString("updateCheck") == "true"; start() }
private fun done(action: ((Boolean) -> Unit) -> Unit) {
val latch = CountDownLatch(1)
var success = false
@@ -30,6 +31,7 @@ class StorageSyncCheck : Instrumentation() {
check(latch.await(45, TimeUnit.SECONDS) && success) { "자료 처리 검증 실패" }
}
override fun onStart() {
if(widgetEntryCheck){WidgetEntryCheck.run(this);return}
if (calendarBridgeCheck) { CalendarBridgeCheck.run(this); return }
if (widgetCheck) { WidgetAppearanceCheck.run(this); return }
if (personalCheck) { PersonalFeatureCheck.run(this, outageCheck); return }
@@ -0,0 +1,68 @@
package kr.co.itosm.dutycalendar
import android.app.Activity
import android.app.Application
import android.app.Instrumentation
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import java.time.LocalDate
/** 실제 Activity 수명과 위젯 진입 경로를 함께 검사한다. 화면은 종료하고 기존 위젯 설정은 바꾸지 않는다. */
object WidgetEntryCheck {
fun run(test:Instrumentation) {
val app=test.targetContext.applicationContext as Application
val alive=mutableSetOf<Activity>()
fun main(action:()->Unit) { var failure:Throwable?=null;test.runOnMainSync{try{action()}catch(error:Throwable){failure=error}};failure?.let{throw it} }
fun awaitUi(condition:()->Boolean) { val end=android.os.SystemClock.uptimeMillis()+5000;while(true){var ready=false;main{ready=condition()};if(ready)return;check(android.os.SystemClock.uptimeMillis()<end){"화면 응답 시간 초과"};android.os.SystemClock.sleep(50)} }
val callbacks=object:Application.ActivityLifecycleCallbacks {
override fun onActivityCreated(a:Activity,s:Bundle?){if(a is MainActivity)alive.add(a)}
override fun onActivityDestroyed(a:Activity){alive.remove(a)}
override fun onActivityStarted(a:Activity){}
override fun onActivityResumed(a:Activity){}
override fun onActivityPaused(a:Activity){}
override fun onActivityStopped(a:Activity){}
override fun onActivitySaveInstanceState(a:Activity,s:Bundle){}
}
app.registerActivityLifecycleCallbacks(callbacks)
var ok=false;var message=""
try {
val snapshotResult=SnapshotCheck.run(app)
val initial=test.startActivitySync(AppNavigation.main(app).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) as MainActivity
test.waitForIdleSync()
val id=WidgetKind.ids(app).firstOrNull()?:error("홈 화면에 검증용 위젯을 먼저 배치해 주세요.")
repeat(3) {
main { app.startActivity(AppNavigation.widgetStyle(app,id).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) }
test.waitForIdleSync()
awaitUi { WidgetStyleDialog.current(initial)!=null }
main {
check(alive.size==1&&alive.single()===initial){"위젯을 눌렀을 때 화면이 ${alive.size}개 생성됐습니다."}
check(!initial.intent.hasExtra("widgetStyleId"))
val dialog=checkNotNull(WidgetStyleDialog.current(initial))
WidgetStyleDialog.show(initial,id);WidgetStyleDialog.show(initial,id)
check(WidgetStyleDialog.current(initial)===dialog){"꾸미기 창 중복 생성"}
}
}
main { WidgetStyleDialog.dismiss(initial);check(WidgetStyleDialog.current(initial)==null) }
val date=LocalDate.of(2027,12,15)
main { app.startActivity(AppNavigation.date(app,date).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) }
test.waitForIdleSync()
fun labels(view:View):List<String> = (if(view is TextView)listOf(view.text.toString()) else emptyList())+
(if(view is ViewGroup)(0 until view.childCount).flatMap{labels(view.getChildAt(it))} else emptyList())
awaitUi { labels(initial.window.decorView).contains("2027. 12") }
main {
check(alive.size==1&&alive.single()===initial)
check(labels(initial.window.decorView).contains("2027. 12")){"재사용한 화면에 날짜 이동이 반영되지 않았습니다."}
check(!initial.intent.hasExtra("selectedDate"))
app.startActivity(AppNavigation.main(app).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK).putExtra("selectedDate","+999999999-12-31").putExtra("widgetStyleId",-100))
}
test.waitForIdleSync()
main { check(alive.size==1);check(WidgetStyleDialog.current(initial)==null);check(labels(initial.window.decorView).contains("2027. 12")) }
ok=true;message="위젯 연속 진입 3회에도 Activity와 꾸미기 창 각각 1개. 한 번 닫기와 기존 화면 날짜 이동 및 잘못된 입력 무시 확인. $snapshotResult"
}catch(error:Throwable){message=error.stackTraceToString()}
finally {main { alive.toList().forEach{it.finish()} };app.unregisterActivityLifecycleCallbacks(callbacks)}
test.finish(if(ok)Activity.RESULT_OK else Activity.RESULT_CANCELED,Bundle().apply{putString("stream",message)})
}
}
+2 -2
View File
@@ -12,8 +12,8 @@
<uses-permission android:name="android.permission.READ_CALENDAR" />
<uses-permission android:name="android.permission.WRITE_CALENDAR" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<application android:label="당직근무" android:icon="@drawable/ic_calendar" android:theme="@style/AppTheme" android:allowBackup="true" android:supportsRtl="true">
<activity android:name=".MainActivity" android:exported="true">
<application android:label="당직근무" android:icon="@drawable/ic_calendar" android:theme="@style/AppTheme" android:allowBackup="true" android:fullBackupContent="@xml/backup_rules" android:dataExtractionRules="@xml/data_extraction_rules" android:usesCleartextTraffic="false" android:supportsRtl="true">
<activity android:name=".MainActivity" android:exported="true" android:launchMode="singleTop">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
@@ -0,0 +1,29 @@
package kr.co.itosm.dutycalendar
import android.content.Context
import android.content.Intent
import android.net.Uri
import java.time.LocalDate
/** 위젯에서 반복해서 열어도 기존 달력 화면으로 돌아간다.
* URI는 날짜와 위젯별 PendingIntent를 구분하는 용도다. 실제 입력은 MainActivity에서
* 다시 검사하며 이미 처리한 값은 Intent에서 지워 화면 복원 때 재실행하지 않는다.
*/
object AppNavigation {
fun main(context:Context)=Intent(context,MainActivity::class.java)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
fun date(context:Context,date:LocalDate)=main(context)
.setData(Uri.parse("dutycalendar://date/$date")).putExtra("selectedDate",date.toString())
fun widgetStyle(context:Context,id:Int)=main(context)
.setData(Uri.parse("dutycalendar://widget/$id/style")).putExtra("widgetStyleId",id)
fun takeDate(intent:Intent):LocalDate? {
val date=runCatching{intent.getStringExtra("selectedDate")?.takeIf{it.length==10}?.let(LocalDate::parse)?.takeIf{it.year in 1900..2199}}.getOrNull()
intent.removeExtra("selectedDate")
return date
}
fun takeWidget(intent:Intent):Int? {
val id=runCatching{if(intent.hasExtra("widgetStyleId"))intent.getIntExtra("widgetStyleId",-1).takeIf{it>0} else null}.getOrNull()
intent.removeExtra("widgetStyleId")
return id
}
}
@@ -34,7 +34,17 @@ object CalendarMirror {
private var waiting:ScheduledFuture<*>?=null
fun prefs(context:Context)=context.getSharedPreferences("calendar_mirror",0)
fun allowed(context:Context)=listOf(Manifest.permission.READ_CALENDAR,Manifest.permission.WRITE_CALENDAR).all{context.checkSelfPermission(it)==PackageManager.PERMISSION_GRANTED}
fun enabled(context:Context)=prefs(context).getBoolean("enabled",false)
fun enabled(context:Context):Boolean {
val settings=prefs(context)
if(!settings.getBoolean("enabled",false))return false
// 예전 백업에는 다른 휴대폰의 달력 번호가 들어 있을 수 있다. 백업되지 않는
// 기기 표식이 없거나 일치하지 않으면 자동 쓰기를 시작하지 않고 다시 선택하게 한다.
val identity=File(context.noBackupFilesDir,"calendar-mirror-owner")
val value=runCatching{identity.readText().trim().also{UUID.fromString(it)}}.getOrNull()?:return false
val bound=settings.getString("owner",null)
if(bound==null)return settings.edit().putString("owner",value).commit()
return bound==value
}
private fun owner(context:Context):String {
val file=File(context.noBackupFilesDir,"calendar-mirror-owner")
if(!file.exists())file.writeText(UUID.randomUUID().toString())
@@ -47,13 +57,17 @@ object CalendarMirror {
waiting=executor.schedule({refresh(app)},800,TimeUnit.MILLISECONDS)
}
fun schedule(context:Context) {
if(enabled(context))context.getSystemService(JobScheduler::class.java).schedule(JobInfo.Builder(JOB,ComponentName(context,CalendarMirrorService::class.java)).setPersisted(true).setPeriodic(24*60*60*1000L).build())
val scheduler=context.getSystemService(JobScheduler::class.java)
if(!enabled(context)){scheduler.cancel(JOB);return}
val period=24*60*60*1000L
// 저장할 때마다 예약을 교체하면 다음 실행 시점이 계속 밀린다. 같은 주기의 기존 작업은 유지한다.
if(scheduler.getPendingJob(JOB)?.intervalMillis!=period)scheduler.schedule(JobInfo.Builder(JOB,ComponentName(context,CalendarMirrorService::class.java)).setPersisted(true).setPeriodic(period).build())
}
fun run(context:Context,finished:(Boolean)->Unit) { executor.execute{finished(refresh(context.applicationContext))} }
@Synchronized fun configure(context:Context,calendar:Long,title:String,rotation:Boolean,events:Boolean,anniversaries:Boolean) {
require(!enabled(context)||prefs(context).getLong("calendar",-1)==calendar){"대상 달력을 바꾸려면 기존 자동 반영을 먼저 해제해 주세요."}
require(rotation||events||anniversaries){"반영할 항목을 하나 이상 선택해 주세요."}
check(prefs(context).edit().putLong("calendar",calendar).putString("title",title).putBoolean("rotation",rotation).putBoolean("events",events).putBoolean("anniversaries",anniversaries).putBoolean("enabled",true).commit())
check(prefs(context).edit().putLong("calendar",calendar).putString("owner",owner(context)).putString("title",title).putBoolean("rotation",rotation).putBoolean("events",events).putBoolean("anniversaries",anniversaries).putBoolean("enabled",true).commit())
request(context)
}
fun stop(context:Context,remove:Boolean,done:(Boolean)->Unit) {
@@ -108,14 +122,15 @@ object CalendarMirror {
internal fun projection(context:Context,today:LocalDate,rotation:Boolean,events:Boolean,anniversaries:Boolean):List<MirroredEvent> {
val first=today.minusDays(30);val last=today.plusDays(366);val schedule=ScheduleStore.load(context)
val output=linkedMapOf<String,MirroredEvent>();val items=PlannerStore.items(context).filter{it.getString("kind")=="event"}
val snapshot=CalendarSnapshot.load(context);val configured=ScheduleStore.isConfigured(context)
fun add(event:MirroredEvent){output[event.key]=event;require(output.size<=10000){"일정이 10,000개를 넘습니다. 반영할 항목을 줄여 주세요."}}
for(offset in 0L..ChronoUnit.DAYS.between(first,last)){
val day=first.plusDays(offset)
if(rotation&&ScheduleStore.isConfigured(context)){
val names=WorkNames.on(context,day,schedule).joinToString(" · "){it.name}
if(rotation&&configured){
val names=snapshot.workNames(day,schedule).joinToString(" · "){it.name}
add(allDay("rotation:$day",schedule.shiftOn(day).title+(if(names.isNotBlank())" · $names" else ""),"당직근무에서 수정하면 자동으로 반영됩니다.",day))
}
if(anniversaries)for(item in Anniversaries.on(context,day)){val d=item.getJSONObject("data");add(allDay("anniversary:${item.getString("id")}:$day",d.getString("title"),d.getString("notes"),day))}
if(anniversaries)for(item in snapshot.anniversariesOn(day)){val d=item.getJSONObject("data");add(allDay("anniversary:${item.getString("id")}:$day",d.getString("title"),d.getString("notes"),day))}
}
if(events)for(item in items){
val d=item.getJSONObject("data");val rule=PlannerStore.eventRule(d)
@@ -0,0 +1,42 @@
package kr.co.itosm.dutycalendar
import android.content.Context
import org.json.JSONObject
import java.time.LocalDate
/** 날짜마다 전체 JSON과 암호화된 로그인 정보를 다시 읽지 않도록 표시 시작 때 한 번 모은다.
* 화면 또는 위젯 한 번을 그리는 동안만 사용한다. 전역 캐시가 아니므로 다음 갱신에서는
* 최신 자료와 로그인 상태를 다시 확인하며 회원 전용 자료가 로그아웃 뒤 남지 않는다.
*/
class CalendarSnapshot internal constructor(context:Context,items:List<JSONObject>,company:JSONObject?,val connected:Boolean) {
private val app=context.applicationContext
val people=if(connected)People.from(items,company) else emptyList()
private val peopleById=people.associateBy{it.id}
private val events=items.filter{it.getString("kind")=="event"}.mapNotNull{item->
runCatching{item to PlannerStore.eventRule(item.getJSONObject("data"))}.getOrNull()
}.sortedWith(compareBy<Pair<JSONObject,EventRepeat>>{!it.first.getJSONObject("data").getBoolean("allDay")}
.thenBy{it.first.getJSONObject("data").getString("startTime")}.thenBy{it.first.getJSONObject("data").getString("title")})
private val anniversaries=if(connected)items.filter{it.getString("kind")=="anniversary"}.sortedBy{it.getJSONObject("data").getString("title")}
.mapNotNull{item->runCatching{item to Anniversaries.rule(item.getJSONObject("data"))}.getOrNull()} else emptyList()
private val names=if(connected)items.filter{it.getString("kind")=="name_rule"}.mapNotNull{item->
runCatching{val data=item.getJSONObject("data");if(data.optBoolean("enabled"))data to WorkNames.rule(data) else null}.getOrNull()
} else emptyList()
val hasNames get()=names.isNotEmpty()
fun eventsOn(date:LocalDate)=events.filter{it.second.occurrenceOn(date)!=null}.map{it.first}
fun anniversariesOn(date:LocalDate):List<JSONObject> {
val lunar by lazy{LunarDates.day(app,date)}
return anniversaries.filter{it.second.matches(date,if(it.second.calendar=="LUNAR")lunar else null)}.map{it.first}
}
fun workNames(date:LocalDate,schedule:Schedule):List<WorkName> = names.mapNotNull{(data,rule)->
val person=peopleById[data.optString("personId")]
if(!rule.matches(date,schedule.shiftOn(date),Holidays.name(app,date)!=null,person?.schedule?.shiftOn(date)))null
else WorkName(if(data.getString("mode")=="PERSON")person!!.name else data.getString("name"),People.colors.getValue(data.getString("color")).second)
}.distinctBy{it.name}
companion object {
fun load(context:Context):CalendarSnapshot {
val connected=SyncClient.connected(context)
val (items,company)=PlannerStore.displayData(context)
return CalendarSnapshot(context,items,company,connected)
}
}
}
@@ -28,12 +28,13 @@ object CompactWidgetViews {
return base.plusDays(context.getSharedPreferences("widget",0).getInt("offset_$id",0).toLong())
}
private fun dateIntent(context:Context,id:Int,date:LocalDate)=PendingIntent.getActivity(context,id,
Intent(context,MainActivity::class.java).setData(Uri.parse("dutycalendar://date/$date")).putExtra("selectedDate",date.toString()),
AppNavigation.date(context,date),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
fun build(context:Context,id:Int,kind:WidgetKind,width:Int,height:Int):RemoteViews {
val style=WidgetStyle.load(context,id)
val schedule=ScheduleStore.load(context)
val snapshot=CalendarSnapshot.load(context)
val today=LocalDate.now()
val density=context.resources.displayMetrics.density
val layout=when(kind){WidgetKind.WIDE->R.layout.duty_widget_wide;WidgetKind.TALL->R.layout.duty_widget_tall;else->R.layout.duty_widget_today}
@@ -44,7 +45,7 @@ object CompactWidgetViews {
views.setTextColor(R.id.compact_title,style.ink)
views.setTextColor(R.id.compact_customize,style.ink)
views.setTextViewTextSize(R.id.compact_title,TypedValue.COMPLEX_UNIT_SP,if(kind==WidgetKind.WIDE)14f else 12f)
val customize=Intent(context,MainActivity::class.java).setData(Uri.parse("dutycalendar://widget/$id/style")).putExtra("widgetStyleId",id)
val customize=AppNavigation.widgetStyle(context,id)
views.setOnClickPendingIntent(R.id.compact_customize,PendingIntent.getActivity(context,id,customize,PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE))
if(kind==WidgetKind.TODAY) {
@@ -59,7 +60,7 @@ object CompactWidgetViews {
views.setTextColor(R.id.compact_tomorrow,style.ink)
views.setTextViewTextSize(R.id.compact_tomorrow,TypedValue.COMPLEX_UNIT_SP,11f*scale)
views.setOnClickPendingIntent(R.id.compact_tomorrow,dateIntent(context,id,today.plusDays(1)))
val details=detail(context,today,schedule,style)
val details=detail(context,today,schedule,style,snapshot)
views.setTextViewText(R.id.compact_detail,details.ifBlank{"당직근무"})
views.setTextColor(R.id.compact_detail,style.muted)
views.setContentDescription(R.id.compact_shift,"${today} ${schedule.shiftOn(today).title}. $details")
@@ -79,12 +80,12 @@ object CompactWidgetViews {
val date=first.plusDays(index.toLong())
val shift=schedule.shiftOn(date)
val holiday=Holidays.name(context,date)
val events=PlannerStore.eventsOn(context,date)
val anniversaries=Anniversaries.on(context,date)
val events=snapshot.eventsOn(date)
val anniversaries=snapshot.anniversariesOn(date)
val plus=if(style.eventMark&&(events.isNotEmpty()||anniversaries.isNotEmpty()))"+" else ""
val dateLabel=if(kind==WidgetKind.WIDE)date.dayOfMonth.toString()+plus else date.format(DateTimeFormatter.ofPattern("M.d E",Locale.KOREAN))+plus
val shiftLabel=if(kind==WidgetKind.WIDE)shift.shortTitle else shift.title
val extra=if(kind==WidgetKind.TALL&&height>=380&&style.detail!="COMPACT")detail(context,date,schedule,style) else ""
val extra=if(kind==WidgetKind.TALL&&height>=380&&style.detail!="COMPACT")detail(context,date,schedule,style,snapshot) else ""
val separator=if(kind==WidgetKind.WIDE)"\n" else " "
val text=dateLabel+separator+shiftLabel+(if(extra.isNotBlank())"\n$extra" else "")
val styled=SpannableString(text)
@@ -103,18 +104,18 @@ object CompactWidgetViews {
views.setTextViewTextSize(cell,TypedValue.COMPLEX_UNIT_SP,minOf(font*style.scale/100,lineLimit.coerceAtLeast(8f)))
views.setInt(cell,"setBackgroundColor",if(date==today&&style.today)(if(style.dark)0x554A6D96 else 0x44A7B5CB) else 0)
views.setOnClickPendingIntent(cell,dateIntent(context,id,date))
views.setContentDescription(cell,"${date} ${shift.title}. ${holiday.orEmpty()} 일정 ${events.size}개. 기념일 ${anniversaries.size}개. ${detail(context,date,schedule,style)}")
views.setContentDescription(cell,"${date} ${shift.title}. ${holiday.orEmpty()} 일정 ${events.size}개. 기념일 ${anniversaries.size}개. ${detail(context,date,schedule,style,snapshot)}")
}
return views
}
private fun detail(context:Context,date:LocalDate,schedule:Schedule,style:WidgetStyle):String {
private fun detail(context:Context,date:LocalDate,schedule:Schedule,style:WidgetStyle,snapshot:CalendarSnapshot):String {
val values=mutableListOf<String>()
if(style.people)values.addAll(WorkNames.on(context,date,schedule).map{it.name})
if(style.people)values.addAll(snapshot.workNames(date,schedule).map{it.name})
if(style.lunar&&schedule.showLunar)LunarDates.label(context,date)?.let{values.add(it)}
if(style.holidays)Holidays.name(context,date)?.let{values.add(it)}
if(style.anniversaries)Anniversaries.on(context,date).firstOrNull()?.let{values.add(it.getJSONObject("data").getString("title"))}
if(style.people)People.onDuty(People.all(context),date).firstOrNull()?.let{values.add(it.name)}
if(style.eventMark)PlannerStore.eventsOn(context,date).size.takeIf{it>0}?.let{values.add("일정 ${it}개")}
if(style.anniversaries)snapshot.anniversariesOn(date).firstOrNull()?.let{values.add(it.getJSONObject("data").getString("title"))}
if(style.people)People.onDuty(snapshot.people,date).firstOrNull()?.let{values.add(it.name)}
if(style.eventMark)snapshot.eventsOn(date).size.takeIf{it>0}?.let{values.add("일정 ${it}개")}
return values.joinToString(" · ")
}
}
@@ -58,7 +58,7 @@ open class DutyWidget : AppWidgetProvider() {
} 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)
manager.getAppWidgetIds(ComponentName(context,javaClass)).forEach{update(context,manager,it)}
}
}
@@ -85,6 +85,9 @@ open class DutyWidget : AppWidgetProvider() {
val manager = AppWidgetManager.getInstance(context)
WidgetKind.ids(context).forEach { update(context, manager, it) }
}
fun updateOne(context:Context,id:Int) {
if(id in WidgetKind.ids(context))update(context,AppWidgetManager.getInstance(context),id)
}
private fun update(context: Context, manager: AppWidgetManager, id: Int) {
val options=manager.getAppWidgetOptions(id)
val kind=WidgetKind.of(context,id)
@@ -114,7 +117,8 @@ open class DutyWidget : AppWidgetProvider() {
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 snapshot=CalendarSnapshot.load(context)
val people = if(style.people&&!compact)snapshot.people else emptyList()
val today = LocalDate.now()
val configured = ScheduleStore.isConfigured(context)
val view = RemoteViews(context.packageName, R.layout.duty_widget)
@@ -130,12 +134,12 @@ open class DutyWidget : AppWidgetProvider() {
view.setTextColor(headers[index], when(day) { 0 -> style.color(0xFFBD5163.toInt()); 6 -> style.color(schedule.saturdayColor); else -> style.muted })
}
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)
val customize=AppNavigation.widgetStyle(context,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)
val open = PendingIntent.getActivity(context, 0, AppNavigation.main(context), PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
view.setOnClickPendingIntent(R.id.widget_root, open)
// 같은 동작도 위젯 번호별로 다른 PendingIntent를 사용한다. 다른 위젯의 월을 바꾸지 않기 위해서다.
// 명시적 수신 대상과 변경 불가 플래그를 사용해 홈 화면 앱이 전달 내용을 바꾸지 못하게 한다.
@@ -146,14 +150,14 @@ open class DutyWidget : AppWidgetProvider() {
calendarDays(month, schedule.weekStart).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 events = snapshot.eventsOn(date)
val personalDays = snapshot.anniversariesOn(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 workNames = if (style.people && !compact) WorkNames.on(context, date, schedule) else emptyList()
val workNames = if (style.people && !compact) snapshot.workNames(date, schedule) else emptyList()
val workLabel = workNames.take(2).joinToString("\n") { it.name.take(5) }
val baseText = "$heading\n${shift.shortTitle}" + (if (workLabel.isNotBlank()) "\n$workLabel" else "") + (holidayShort?.let { "\n$it" } ?: "")
val colleagues = People.onDuty(people, date)
@@ -200,7 +204,7 @@ open class DutyWidget : AppWidgetProvider() {
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())
val dayIntent = AppNavigation.date(context,date)
view.setOnClickPendingIntent(cellId, PendingIntent.getActivity(context, id * 1000 + index + 1, dayIntent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE))
}
return view
@@ -66,17 +66,27 @@ class MainActivity : Activity() {
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)) }
if(savedInstanceState==null) receiveNavigation(intent)
}
private fun receiveNavigation(incoming:android.content.Intent) {
AppNavigation.takeDate(incoming)?.let { selectedDate=it;month=YearMonth.from(it) }
AppNavigation.takeWidget(incoming)?.let { id -> window.decorView.post {
if(!isFinishing&&!isDestroyed)WidgetStyleDialog.show(this,id)
} }
}
override fun onNewIntent(incoming:android.content.Intent) {
super.onNewIntent(incoming)
setIntent(incoming);receiveNavigation(incoming)
}
override fun onDestroy() { WidgetStyleDialog.dismiss(this);super.onDestroy() }
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)
CalendarMirror.request(this)
Holidays.schedule(this)
Holidays.refresh(this) { success -> if (success) runOnUiThread { if (!isFinishing && !isDestroyed) render() } }
val holidayRevision=Holidays.revision(this)
Holidays.refresh(this) { success -> if (success&&Holidays.revision(this)!=holidayRevision) runOnUiThread { if (!isFinishing && !isDestroyed) render() } }
SyncClient.schedule(this)
SyncClient.foreground(this) { runOnUiThread { if (!isFinishing && !isDestroyed) render() } }
UpdateChecker.check(this, fresh = true)
@@ -99,7 +109,8 @@ class MainActivity : Activity() {
val schedule = ScheduleStore.load(this)
val configured = ScheduleStore.isConfigured(this)
val today = LocalDate.now()
val people = People.all(this)
val snapshot = CalendarSnapshot.load(this)
val people = snapshot.people
val scroll = ScrollView(this).apply {
isFillViewport = true; setBackgroundColor(0xFFF4F1EA.toInt())
setOnScrollChangeListener { _, _, y, _, _ -> if (!restoringScroll && generation == renderGeneration) scrollOffset = y }
@@ -164,9 +175,9 @@ class MainActivity : Activity() {
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 workNames = WorkNames.on(this, date, schedule)
val events = snapshot.eventsOn(date)
val personalDays = snapshot.anniversariesOn(date)
val workNames = snapshot.workNames(date, schedule)
val colleagues = People.onDuty(people, date)
val inside = YearMonth.from(date) == month
val cell = column().apply {
@@ -207,7 +218,7 @@ class MainActivity : Activity() {
}.setNegativeButton("닫기", null).show()
}
}
cells.addView(cell, LinearLayout.LayoutParams(0, dp((if (people.isEmpty() && WorkNames.rules(this).isEmpty()) 103 else 174) + if (schedule.showLunar) 14 else 0), 1f))
cells.addView(cell, LinearLayout.LayoutParams(0, dp((if (people.isEmpty() && !snapshot.hasNames) 103 else 174) + if (schedule.showLunar) 14 else 0), 1f))
}
calendar.addView(View(this).apply { setBackgroundColor(0xFFE6E4DC.toInt()) }, LinearLayout.LayoutParams(-1, dp(1)))
calendar.addView(cells)
@@ -458,6 +469,10 @@ class MainActivity : Activity() {
override fun onRequestPermissionsResult(requestCode:Int,permissions:Array<out String>,grantResults:IntArray) {
super.onRequestPermissionsResult(requestCode,permissions,grantResults)
deviceCalendar.permissionResult(requestCode,grantResults)
if(requestCode==CalendarMirrorDialogs.REQUEST) {
if(CalendarMirror.allowed(this))CalendarMirrorDialogs(this).open()
else Toast.makeText(this,"기본 달력 자동 반영에는 달력 읽기와 쓰기 권한이 필요합니다.",Toast.LENGTH_LONG).show()
}
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()
@@ -46,7 +46,7 @@ object MonthWidgetViews {
val views=RemoteViews(context.packageName,R.layout.duty_widget_month_fit)
views.setInt(R.id.widget_root,"setBackgroundColor",style.background)
views.setViewPadding(R.id.widget_root,(padding*density).toInt(),(padding*density).toInt(),(padding*density).toInt(),(padding*density).toInt())
val open=PendingIntent.getActivity(context,0,Intent(context,MainActivity::class.java),PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
val open=PendingIntent.getActivity(context,0,AppNavigation.main(context),PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
views.setOnClickPendingIntent(R.id.widget_root,open)
views.setTextViewText(R.id.widget_title,if(width<180)"${month.year}.${month.monthValue}" else "${month.year}년 ${month.monthValue}월")
val titleFont=if(width<180||short)11f else 17f
@@ -55,7 +55,7 @@ object MonthWidgetViews {
views.setTextColor(control,style.ink)
views.setTextViewTextSize(control,TypedValue.COMPLEX_UNIT_DIP,if(control==R.id.widget_title)titleFont else 9f)
}
val customize=Intent(context,MainActivity::class.java).setData(Uri.parse("dutycalendar://widget/$id/style")).putExtra("widgetStyleId",id)
val customize=AppNavigation.widgetStyle(context,id)
views.setOnClickPendingIntent(R.id.widget_customize,PendingIntent.getActivity(context,id,customize,PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE))
val headers=intArrayOf(R.id.widget_sun,R.id.widget_mon,R.id.widget_tue,R.id.widget_wed,R.id.widget_thu,R.id.widget_fri,R.id.widget_saturday)
calendarWeekdays(schedule.weekStart).forEachIndexed { index,day ->
@@ -73,13 +73,14 @@ object MonthWidgetViews {
val intent=Intent(context,kind.receiver).setAction(action).putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,id)
views.setOnClickPendingIntent(control,PendingIntent.getBroadcast(context,id,intent,PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE))
}
val people=if(style.people)People.all(context) else emptyList()
val snapshot=CalendarSnapshot.load(context)
val people=if(style.people)snapshot.people else emptyList()
calendarDays(month,schedule.weekStart).forEachIndexed { index,date ->
val shift=schedule.shiftOn(date)
val holiday=Holidays.name(context,date)
val events=PlannerStore.eventsOn(context,date)
val anniversaries=Anniversaries.on(context,date)
val names=if(style.people)WorkNames.on(context,date,schedule) else emptyList()
val events=snapshot.eventsOn(date)
val anniversaries=snapshot.anniversariesOn(date)
val names=if(style.people)snapshot.workNames(date,schedule) else emptyList()
val colleagues=People.onDuty(people,date)
val lunar=if(style.lunar&&schedule.showLunar)LunarDates.label(context,date) else null
val extra=names.firstOrNull()?.name
@@ -122,7 +123,7 @@ object MonthWidgetViews {
}
views.setInt(cell,"setBackgroundColor",background)
views.setContentDescription(cell,"${date.year}년 ${date.monthValue}월 ${date.dayOfMonth}일 ${shift.title}. ${holiday.orEmpty()} ${lunar.orEmpty()}. 이름 ${names.joinToString{it.name}}. 함께 당직 ${colleagues.joinToString{it.name}}. 일정 ${events.size}개. 기념일 ${anniversaries.joinToString{it.getJSONObject("data").getString("title")}}")
val intent=Intent(context,MainActivity::class.java).setData(Uri.parse("dutycalendar://date/$date")).putExtra("selectedDate",date.toString())
val intent=AppNavigation.date(context,date)
views.setOnClickPendingIntent(cell,PendingIntent.getActivity(context,id*1000+index+1,intent,PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE))
}
return views
@@ -18,16 +18,20 @@ object People {
fun all(context: Context): List<PersonDuty> {
// 회원 연결이 꺼지면 보관 자료를 지우지 않고 표시에서 제외한다. 위젯도 이 경로를 사용한다.
if (!SyncClient.connected(context)) return emptyList()
return PlannerStore.items(context).filter { it.getString("kind") == "person" }.mapNotNull { item ->
val (items,company)=PlannerStore.displayData(context)
return from(items,company)
}
internal fun from(items:List<JSONObject>,company:JSONObject?):List<PersonDuty> {
return items.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 }
}.plus(shared(company)).sortedBy { it.name }
}
private fun shared(context: Context): List<PersonDuty> {
val members = PlannerStore.company(context)?.optJSONArray("members") ?: return emptyList()
private fun shared(company: JSONObject?): List<PersonDuty> {
val members = company?.optJSONArray("members") ?: return emptyList()
return PlannerStore.list(members).filter { !it.optBoolean("isSelf") }.mapNotNull { person ->
runCatching {
val rotation = person.getJSONObject("rotation")
@@ -42,11 +42,18 @@ object PlannerStore {
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)
return visibleItems(read(context))
}
private fun visibleItems(document:JSONObject):List<JSONObject> {
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") }
}
/** 한 화면을 만드는 동안 같은 원본과 전송 대기 내용을 함께 읽는다. 반환 객체는 화면 전용이며 저장에 재사용하지 않는다. */
@Synchronized fun displayData(context:Context):Pair<List<JSONObject>,JSONObject?> {
val document=read(context)
return visibleItems(document) to document.getJSONObject("state").optJSONObject("company")
}
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") })
@@ -63,7 +63,7 @@ object Reminders {
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 open=AppNavigation.date(context,plan.date)
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()
@@ -44,19 +44,33 @@ data class WidgetStyle(
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)
if(id==null)DutyWidget.updateAll(context) else DutyWidget.updateOne(context,id)
}
}
}
object WidgetStyleDialog {
private var opened=java.lang.ref.WeakReference<AlertDialog>(null)
internal fun current(activity:Activity)=opened.get()?.takeIf{it.ownerActivity===activity&&it.isShowing}
fun dismiss(activity:Activity) { current(activity)?.dismiss() }
private fun display(activity:Activity,dialog:AlertDialog) {
opened.get()?.dismiss()
dialog.setOwnerActivity(activity)
opened=java.lang.ref.WeakReference(dialog)
dialog.setOnDismissListener { if(opened.get()===dialog)opened.clear() }
dialog.show()
}
fun show(activity:Activity,id:Int?=null) {
// 빠른 연속 터치와 같은 위젯의 재진입이 겹쳐도 편집 창을 한 개만 유지한다.
// Activity를 강하게 보관하지 않으며 화면 종료 시 현재 창을 함께 닫는다.
if(activity.isFinishing||activity.isDestroyed||current(activity)!=null)return
val ids=WidgetKind.ids(activity)
if(id!=null){if(id in ids)edit(activity,id);return}
if(ids.isEmpty()){edit(activity,null);return}
AlertDialog.Builder(activity).setTitle("꾸밀 위젯 선택")
val picker=AlertDialog.Builder(activity).setTitle("꾸밀 위젯 선택")
.setItems((listOf("모든 위젯과 새 위젯의 기본값")+ids.mapIndexed{index,widgetId->"${WidgetKind.of(activity,widgetId).title} · ${index+1}"}).toTypedArray()){_,index->edit(activity,if(index==0)null else ids[index-1])}
.setNegativeButton("닫기",null).show()
.setNegativeButton("닫기",null).create()
display(activity,picker)
}
private fun edit(activity:Activity,id:Int?) {
val original=WidgetStyle.load(activity,id)
@@ -96,6 +110,6 @@ object WidgetStyleDialog {
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);monthFit.setSelection(0);listOf(lunar,holidays,people,anniversaries,marks,today).forEach{it.isChecked=true};updatePreview()}
}
dialog.show();updatePreview()
display(activity,dialog);updatePreview()
}
}
+9
View File
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- 휴대폰 달력 번호와 위젯 번호 및 설치 세션은 다른 기기로 옮기지 않는다. 개인 근무와 일정은 기존 백업을 유지한다. -->
<full-backup-content>
<exclude domain="sharedpref" path="calendar_mirror.xml" />
<exclude domain="sharedpref" path="widget.xml" />
<exclude domain="sharedpref" path="widget_style.xml" />
<exclude domain="sharedpref" path="web_sync.xml" />
<exclude domain="sharedpref" path="app_update.xml" />
</full-backup-content>
@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<data-extraction-rules>
<cloud-backup>
<exclude domain="sharedpref" path="calendar_mirror.xml" />
<exclude domain="sharedpref" path="widget.xml" />
<exclude domain="sharedpref" path="widget_style.xml" />
<exclude domain="sharedpref" path="web_sync.xml" />
<exclude domain="sharedpref" path="app_update.xml" />
</cloud-backup>
<device-transfer>
<exclude domain="sharedpref" path="calendar_mirror.xml" />
<exclude domain="sharedpref" path="widget.xml" />
<exclude domain="sharedpref" path="widget_style.xml" />
<exclude domain="sharedpref" path="web_sync.xml" />
<exclude domain="sharedpref" path="app_update.xml" />
</device-transfer>
</data-extraction-rules>