Skip to content

Architecture and Storage

Bulbasaur edited this page Dec 3, 2026 · 3 revisions

Architecture and Storage

English · 한국어

This page is for people reading or changing the code: how the app is layered, how the database is shaped, where files live on the device, and how backup and encryption are put together. The decisions themselves are recorded in the repository as ADRs — ADR-0001 and ADR-0002 — and this page is a summary that is kept in step with them.

All identifiers, file names and hashes on this page that look like data are placeholders, not values from any real device.

1. Local storage: from Realm to Room

ADR-0001 chose Realm for local storage. Operating the app showed three things it could not give: a schema that survives code review as a file, value objects that move freely between coroutines and Compose state, and a backup that is easy to serialize. ADR-0002 replaced it:

  • 1.4.351 / 1.4.352 — data moved to Room.
  • 1.4.353 (2026-11-06) — the Realm dependency was removed completely.

The local store is now Room (SQLite) behind a repository layer. ADR-0001 is marked superseded.

2. Layers

Compose screens · Activities · Fragments
        ↓ (Hilt injection)
@HiltViewModel        e.g. DiaryViewModel, PinLockViewModel, SymbolFilterPickerViewModel
        ↓
domain/repository     DiaryRepository, TagRepository, AlarmRepository, DDayRepository, ActionLogRepository (interfaces)
        ↓ (@Binds in RepositoryModule)
data/repository/*Impl domain ↔ entity mapping (RoomMapper), transaction boundary
        ↓
data/datasource       DiaryDataSource and friends, qualified @LocalDataSource / @RemoteDataSource
        ↓
data/local/datasource/*Impl → data/local/dao/*Dao → AppDatabase (Room)

Rules that hold across the code:

  • Domain models are not Room entities. domain/model holds Diary, Tag, Alarm, DDay, ActionLog, … and data/local/mapper/RoomMapper.kt is the only place that converts between the two.
  • The repository owns the transaction boundary. Writes that touch an entry together with its photos and tags run inside database.withTransaction { }, and DAO methods that group several statements are annotated @Transaction.
  • Screens see interfaces. A screen injects DiaryRepository, never a DAO or an entity.
  • UI is Compose-first. New screens are Jetpack Compose; existing XML layouts stay until a screen is refactored, and a new element inside XML is a ComposeView.
  • State is a StateFlow exposed read-only, collected with collectAsStateWithLifecycle().

Migration leftovers are acknowledged in the code rather than hidden: the @RemoteDataSource stubs, the FIXME: Remove temporary code in the repositories, and the Config.enableJetpackRoomDatabase flag.

3. Data model

AppDatabase is at version 9, exportSchema = true. Schema snapshots 1.json … 9.json are committed under app/schemas/me.blog.korn123.easydiary.data.local.AppDatabase/.

Entity Table Key and constraints
DiaryEntity diaries PK diaryId (autoGenerate), index on currentTimeMillis, embeds LocationEntity with @Embedded(prefix = "loc_")
PhotoUriEntity photo_uris PK id, FK diaryId → diaries.diaryId (CASCADE)
AlarmEntity alarms PK alarmId
ActionLogEntity action_logs PK id
DDayEntity d_days PK id
TagEntity tags PK tagId, unique index on normalizedName
DiaryTagCrossRefEntity diary_tag_cross_ref Composite PK (diaryId, tagId), both FKs CASCADE

LocationEntity is not a table of its own: it is flattened into loc_address, loc_latitude and loc_longitude on diaries.

Migrations live in data/local/Migrations.kt (MIGRATION_1_2 … MIGRATION_8_9) and are registered in DatabaseModule.provideAppDatabase(). MIGRATION_7_8 added only the tag tables; MIGRATION_8_9 added the schedule backup options. Changing the schema means: edit the entity → build so KSP writes the new N.json → write the migration → register it → commit all three.

Tags as a many-to-many relation

TagEntity stores the display name and the comparison normalizedName (unique). The naming rule — trimmed, whitespace collapsed, case-insensitive, at most 24 characters — lives only in TagRules (domain/model/Tag.kt), so the picker, the filter bar and the stored rows agree on when two names are the same tag. DiaryWithPhotos reads entry, photos and tags in one query through @Relation + Junction, and tag filtering is an EXISTS (SELECT 1 FROM diary_tag_cross_ref …) so it composes with the keyword, date and symbol conditions in one statement.

4. Where files live

Everything is under the app's private directory — context.applicationInfo.dataDir (/data/user/0/me.blog.korn123.easydiary), which needs no permission on any Android version:

Constant Path (relative to dataDir) Holds
WORKING_DIRECTORY /AAFactory/EasyDiary/ The root of everything the app writes
database easy_diary.db Room database (not under AAFactory)
DIARY_PHOTO_DIRECTORY …/Photos/ Attached photos, camera captures, sketches, custom symbol images
DIARY_POSTCARD_DIRECTORY …/Postcards/ Exported postcards
USER_CUSTOM_FONTS_DIRECTORY …/Fonts/ TTF fonts you added
MARKDOWN_DIRECTORY …/Markdown/ Cached help pages
BACKUP_DB_DIRECTORY …/Backup/Database/ Database backup ZIPs
BACKUP_EXCEL_DIRECTORY …/Backup/Excel/ Excel exports

Photos live in app-private storage rather than shared storage deliberately: the app can read, back up and delete them without a storage permission, and the Android backup rules treat them as app data.

5. Backup format

Database backup

Context.exportRoomData() collects every table through generateRoomDataMap() and writes one ZIP:

easy_diary.db_<yyyyMMdd_HHmmss>.zip
└── easy_diary_all.json          (pretty-printed)
    ├── PREFERENCE
    ├── META
    ├── ACTION_LOG
    ├── ALARM
    ├── D_DAY
    ├── DIARY
    ├── TAGS
    └── DIARY_TAG_CROSS_REF

exportRoomDataWithSAF(uri, password) writes the same bytes to a document the user picked. With a password, ZipHelper.writeEncryptedEntry() writes the same single entry as an AES-256 (zip4j) archive; without one, it is a plain java.util.zip.ZipOutputStream.

Restore

importRoomData(jsonString, isMergeData) is the single place that writes a backup back:

  • Each section is cleared and then inserted — action log, alarms, D-Days, entries, tags, tag links, preferences. The settings are written last.
  • Order matters for foreign keys: entries, then tags, then the tag attachments.
  • Old backups still restore. A file without TAGS / DIARY_TAG_CROSS_REF leaves the tag tables empty; a link that points at a missing entry or tag is skipped.
  • Alarms are re-registered. Every existing alarm is cancelled first (AlarmManager keeps them by id in a PendingIntent, not in the database), the rows are inserted, and the enabled ones are scheduled again. If exact alarms are not allowed, the app posts the notification that says so.
  • A schedule password that cannot be opened on this device is dropped to null and the schedule turned off, and the app reports each one afterwards. Writing the archive unencrypted would defeat the password the user set.
  • The app language is applied afterwards, on the main thread, because AppCompatDelegate recreates attached activities.

A restore file is classified by name: a .zip containing db_ is a database backup (classifyUriByExtension() → ROOM), anything else is not accepted.

Full data backup

FullBackupWorker zips the whole AAFactory/EasyDiary/ tree into one archive (ZipHelper.determineFiles() / compress()), with the optional password handled by the same ZIP helper. FullRecoveryWorker only decompresses — the database is applied afterwards by the user running Recover diary on the snapshot the archive carries. A scheduled external-folder backup runs the same worker with a folder URI instead of a document URI, and names the file easy_diary.zip (overwrite) or easy_diary_yyyyMMdd_HHmmss.zip (timestamped) through a temporary .easy_diary.part so a sync tool never sees a half-written archive.

Before asking for a password on a full restore, ZipHelper.inspectArchive() reads only the ZIP central directory (ZipCentralDirectory.kt, Zip64-aware) and checks that a Backup/Database/ entry exists; a stream that cannot seek falls back to the previous behaviour.

6. Security design

Entry encryption

isEncrypt and encryptKeyHash on diaries mark an encrypted entry. The title and body are encrypted with Jasypt's BasicTextEncryptor, keyed by the 6-digit PIN, and the hash stored is SHA-256(pin) so a later entry can be checked before anything is decrypted. Photo files are not encrypted; the reading screen refuses to show them while the entry is encrypted. Deleting the encryption is a write that also clears isEncrypt.

App lock

The PIN and fingerprint state live in their own SharedPreferences file, aaf_lock_prefs.xml, through a one-time idempotent migration from the older preference files (marker lock_prefs_migrated). Keeping them in one file is what makes it possible to exclude them by file name:

  • data_extraction_rules.xml excludes aaf_lock_prefs.xml from both <cloud-backup> and <device-transfer>.
  • preferenceToJsonString() never writes those keys.
  • A device that reports a fingerprint enrolment that can no longer be used is moved to PIN mode on unlock.

At runtime, an unlocked session is marked by a timestamp (aafPinLockPauseMillis); the app re-locks when it is resumed more than a second after that mark. Recent-apps previews are blocked with FLAG_SECURE while a lock is enabled.

Scheduled backup password

AlarmBackupPasswordCipher seals the password with an AES-256-GCM key in the Android Keystore, stored as:

ks1:<base64 iv>:<base64 ciphertext>

with the fixed associated data easy_diary.backupPassword and no user-authentication requirement — a schedule runs unattended. A legacy plain-text value is still read; an envelope this device cannot open becomes null and turns the schedule off.

Storage access

No storage permission is used. The app writes inside dataDir, and the paths that leave it are all picker-based: ACTION_CREATE_DOCUMENT, ACTION_OPEN_DOCUMENT, ACTION_OPEN_DOCUMENT_TREE (with takePersistableUriPermission for schedule folders), the photo picker (PickMultipleVisualMedia, up to 10) or ACTION_PICK on Android 12 and below, and ACTION_IMAGE_CAPTURE for the camera (the app declares no camera permission; the camera app owns it). Sharing goes through FileProvider. Every file the app shares (postcards, photos, Excel exports, sketches) lives under dataDir, which the <files-path> and <cache-path> entries of provider_paths.xml cover; the <external-path> root went with the storage permission in #335 (v1.4.358 반영 예정).

7. The flavor split

The Google-dependent code is isolated in source sets rather than if branches:

Source set Contents
app/src/main Everything shared: screens, Room, Hilt, the FOSS-safe code
app/src/gms The Google manifest and the Google implementations (Drive, Calendar, sign-in)
app/src/gmsProd The full symbol set: nine arrays and the 292 drawables they name (git-ignored), keys.xml (git-ignored)
app/src/gmsDev The same Google code with two arrays only: the ten weather icons (git-ignored) and a committed keys.xml
app/src/lab Experimental code that reuses gmsProd's sources and resources; not published
app/src/foss The FOSS manifest and FlavorUtils — for example getDiarySymbolMap() returns only weather and tasks
app/src/dummy Stand-ins for the GMS-only helpers (markdown sync) so the FOSS build compiles without the Google sources

BuildConfig.IS_FOSS (and isFossFlavor() / isGmsOrLabFlavor() in Activity.kt) is what the UI checks when a Google-only option must disappear. F-Droid builds from its own recipe in the fdroiddata repository, which patches the Gradle files before building, so changing the shape of the // gms dependency block in app/build.gradle.kts can break that recipe.

8. Version notes

  • Room, JSON backup, Keystore sealing, the external-folder schedule and the optional ZIP passwords are in v1.4.357.
  • Excluding aaf_lock_prefs.xml from the OS backup, turning off a schedule whose password cannot be opened, and the exact-alarm / notification-permission handling are merged into develop for v1.4.358.
  • The legacy storage permission, its 22 permission gates, the <external-path> root and the unused SimpleMobileTools helpers are merged into develop for v1.4.358 (#335); the manifest now declares no storage permission at all.
  • The all-symbol statistics and the writing-time statistics are drawn in Compose from v1.4.358 (#336, #337), replacing the MPAndroidChart bar charts of both.

한국어로 보기 →

Clone this wiki locally