Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,19 @@ repository does not keep a copy.
push. A refused file (too large) is reported and does not hold back sync.
A local library keeps its files on the device (de-duplicated by SHA-256)
and uploads them when it turns on sync.
- **Dates and reminders** (guide 9.4, 11.8): `@明天 9点` completion, date chips
and the picker come with the editor page; the format bar has a date button.
The agenda (library menu → 日程) lists open dated to-dos across the
library, checks them off and opens a note at its task. Reminders are
system alarms (`reminders/Reminders.kt`, `Tasks` in core): set again a
moment after any change, restored after a reboot or update, exact when the
system allows it. Android 13+ asks for notification permission the first
time there is something to remind of; a tapped reminder opens its note.
- **Password-protected notes** (guide 8.4): the editor page shows the lock
panel, asks for the password and seals every edit; the app only ever stores
and syncs the sealed body. Note menu: 设置密码 / 更改密码 / 移除密码 /
立即锁定. Protected notes are found by title only, cannot be shared, and
take no part in the agenda or reminders.
- **Media library**: filters (all, images, video, audio, files, unreferenced,
trash), file name search, a thumbnail grid, and details: preview, the notes
that reference the file, rename, public link (make, copy, revoke),
Expand Down
14 changes: 14 additions & 0 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!-- Installing updates downloaded from the website (the system still asks). -->
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<!-- Reminders of tasks with a date: notify, on time, and again after a reboot. -->
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

<application
android:name=".IvyApp"
Expand Down Expand Up @@ -46,6 +50,16 @@
android:resource="@xml/file_paths" />
</provider>

<!-- Task reminders: alarms fire here; after a reboot or an update they are set again. -->
<receiver
android:name=".reminders.ReminderReceiver"
android:exported="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
</intent-filter>
</receiver>

<!-- The system installer's answer to an update (update/ApkInstaller.kt). -->
<receiver
android:name=".update.InstallResultReceiver"
Expand Down
2 changes: 1 addition & 1 deletion app/src/main/assets/editor/editor.css

Large diffs are not rendered by default.

188 changes: 114 additions & 74 deletions app/src/main/assets/editor/main.js

Large diffs are not rendered by default.

12 changes: 12 additions & 0 deletions app/src/main/kotlin/app/ivynote/android/LibrarySession.kt
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import app.ivynote.android.editor.AttachmentLoader
import app.ivynote.android.editor.EditorHost
import app.ivynote.android.platform.SqliteDocumentStore
import app.ivynote.android.platform.networkAvailable
import app.ivynote.android.reminders.Reminders
import app.ivynote.core.L10n
import app.ivynote.core.AddedFile
import app.ivynote.core.ApiClient
Expand All @@ -30,6 +31,7 @@ import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
Expand Down Expand Up @@ -68,6 +70,15 @@ class LibrarySession private constructor(
engine.onUploaded = { att, file ->
runCatching { AttachmentLoader.store(cache, att.id, file, att.mime) }
}
// Reminders follow the notes: the system's alarms are set again a
// moment after any change (guide 11.8).
scope.launch {
engine.revision.collectLatest {
delay(1_500)
val notes = engine.notes.values.toList()
withContext(Dispatchers.Default) { runCatching { Reminders.schedule(context, ref.id, notes) } }
}
}
}

/**
Expand Down Expand Up @@ -180,6 +191,7 @@ class LibrarySession private constructor(
fun destroy() {
if (closed) return
closed = true
Reminders.clear(context, ref.id)
deactivate()
engine.stop()
editorHost?.destroy()
Expand Down
59 changes: 59 additions & 0 deletions app/src/main/kotlin/app/ivynote/android/MainActivity.kt
Original file line number Diff line number Diff line change
@@ -1,19 +1,78 @@
package app.ivynote.android

import android.Manifest
import android.content.Intent
import android.os.Build
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import app.ivynote.android.reminders.Reminders
import app.ivynote.android.ui.IvyTheme
import app.ivynote.android.ui.ProvideStrings
import app.ivynote.android.ui.RootScreen
import kotlinx.coroutines.flow.MutableStateFlow

class MainActivity : ComponentActivity() {
private val askNotifications = registerForActivityResult(ActivityResultContracts.RequestPermission()) { }

override fun onCreate(savedInstanceState: Bundle?) {
enableEdgeToEdge()
super.onCreate(savedInstanceState)
Reminders.ensureChannel(this)
Reminders.onScheduled = { runOnUiThread { askForNotificationsOnce() } }
handle(intent)
setContent {
ProvideStrings { IvyTheme { RootScreen() } }
}
}

override fun onDestroy() {
Reminders.onScheduled = null
super.onDestroy()
}

override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
handle(intent)
}

override fun onResume() {
super.onResume()
askForNotificationsOnce()
}

/** A tapped reminder opens its note (LibraryScreen picks the request up). */
private fun handle(intent: Intent?) {
val note = intent?.getStringExtra(EXTRA_NOTE) ?: return
val library = intent.getStringExtra(EXTRA_LIBRARY) ?: return
openRequest.value = OpenRequest(library, note)
intent.removeExtra(EXTRA_NOTE)
}

/**
* Android 13+ asks before an app may notify. The question comes once, the
* first time a library has a reminder to come, not at the first start.
*/
private fun askForNotificationsOnce() {
if (Build.VERSION.SDK_INT < 33 || Reminders.mayNotify(this)) return
val prefs = getSharedPreferences("ivy.app", MODE_PRIVATE)
if (prefs.getBoolean(ASKED, false)) return
val any = getSharedPreferences("ivy.reminders", MODE_PRIVATE).all.values.any { ((it as? String)?.length ?: 0) > 2 }
if (!any) return
prefs.edit().putBoolean(ASKED, true).apply()
askNotifications.launch(Manifest.permission.POST_NOTIFICATIONS)
}

data class OpenRequest(val library: String, val note: String)

companion object {
const val EXTRA_LIBRARY = "app.ivynote.library"
const val EXTRA_NOTE = "app.ivynote.note"
private const val ASKED = "notificationsAsked"

/** A note to open, from a tapped reminder. */
val openRequest = MutableStateFlow<OpenRequest?>(null)
}
}
19 changes: 19 additions & 0 deletions app/src/main/kotlin/app/ivynote/android/editor/EditorHost.kt
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import app.ivynote.core.Language
import app.ivynote.core.Attachment
import app.ivynote.core.IvyJson
import app.ivynote.core.Note
import app.ivynote.core.NoteLock
import app.ivynote.core.SyncEngine
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
Expand Down Expand Up @@ -90,6 +91,15 @@ class EditorHost(appContext: Context, private val session: LibrarySession) {
private val _topLine = MutableStateFlow(0)
val topLine: StateFlow<Int> = _topLine.asStateFlow()

/** Whether the open note has a password (guide 8.4), and is locked now. */
data class Protection(val protected: Boolean = false, val locked: Boolean = false)

private val _protection = MutableStateFlow(Protection())
val protection: StateFlow<Protection> = _protection.asStateFlow()

/** The insert menu asks for a photo ("image") or a file ("file"). */
var onPick: ((String) -> Unit)? = null

/** A followed `[[wiki link]]`: id ("" when no such note) and title. */
var onOpenNote: ((String, String) -> Unit)? = null

Expand Down Expand Up @@ -119,6 +129,8 @@ class EditorHost(appContext: Context, private val session: LibrarySession) {
fun open(note: Note, focus: Boolean) {
noteId = note.id
pageBody = note.body
val sealed = NoteLock.isEncrypted(note.body)
_protection.value = Protection(protected = sealed, locked = sealed)
_topLine.value = 0
sendTitles()
refreshKinds()
Expand Down Expand Up @@ -243,6 +255,13 @@ class EditorHost(appContext: Context, private val session: LibrarySession) {
}
"open" -> onOpenNote?.invoke(m.str("id").orEmpty(), m.str("title").orEmpty())
"focus" -> _focused.value = (m["focused"] as? JsonPrimitive)?.booleanOrNull ?: false
"pick" -> onPick?.invoke(m.str("kind").orEmpty())
"protection" -> if (m.str("id") == noteId) {
_protection.value = Protection(
protected = (m["protected"] as? JsonPrimitive)?.booleanOrNull ?: false,
locked = (m["locked"] as? JsonPrimitive)?.booleanOrNull ?: false,
)
}
"scroll" -> _topLine.value = (m["line"] as? JsonPrimitive)?.intOrNull ?: 0
"error", "log" -> if (BuildConfig.DEBUG) Log.d("ivy", "page ${m.str("type")}: ${m.str("message")}")
}
Expand Down
165 changes: 165 additions & 0 deletions app/src/main/kotlin/app/ivynote/android/reminders/Reminders.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
package app.ivynote.android.reminders

import android.Manifest
import android.app.AlarmManager
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat
import app.ivynote.android.MainActivity
import app.ivynote.android.R
import app.ivynote.core.IvyJson
import app.ivynote.core.L10n
import app.ivynote.core.Note
import app.ivynote.core.Tasks
import app.ivynote.core.nowMillis
import kotlinx.serialization.Serializable
import kotlinx.serialization.builtins.ListSerializer
import java.time.LocalTime

/**
* Reminders for tasks with a 📅 date (guide 9.4, 11.8). Whenever a library's
* notes change, the next reminders of that library are handed to the
* system's AlarmManager, so they fire while the app is closed. They are also
* kept in preferences, to be set again after a reboot or an app update.
* Protected notes take no part: their tasks are encrypted.
*/
object Reminders {
const val CHANNEL = "reminders"
private const val PREFS = "ivy.reminders"
private const val ACTION = "app.ivynote.REMINDER"
/** How far ahead alarms are set; changes reschedule anyway. */
private const val HORIZON_MS = 8L * 24 * 3600 * 1000
private const val MAX = 48
/** A date without a time reminds at this hour (as the web's default). */
val ALL_DAY: LocalTime = LocalTime.of(9, 0)

@Serializable
data class Pending(val key: String, val library: String, val noteId: String, val title: String, val text: String, val at: Long)

/** Called after alarms were set for at least one reminder (any thread). */
@Volatile var onScheduled: (() -> Unit)? = null

private fun prefs(context: Context) = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)

private fun load(context: Context, library: String): List<Pending> =
prefs(context).getString(library, null)?.let { runCatching { IvyJson.decodeFromString(ListSerializer(Pending.serializer()), it) }.getOrNull() } ?: emptyList()

private fun save(context: Context, library: String, list: List<Pending>) {
prefs(context).edit().putString(library, IvyJson.encodeToString(ListSerializer(Pending.serializer()), list)).apply()
}

fun ensureChannel(context: Context) {
val nm = context.getSystemService(NotificationManager::class.java) ?: return
val ch = NotificationChannel(CHANNEL, L10n.s.reminderChannel, NotificationManager.IMPORTANCE_HIGH)
ch.description = L10n.s.reminderChannelHint
nm.createNotificationChannel(ch)
}

private fun intent(context: Context, p: Pending): PendingIntent {
val i = Intent(context, ReminderReceiver::class.java).setAction(ACTION)
.putExtra("key", p.key).putExtra("library", p.library).putExtra("note", p.noteId)
.putExtra("title", p.title).putExtra("text", p.text)
return PendingIntent.getBroadcast(context, p.key.hashCode(), i, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
}

private fun set(context: Context, p: Pending) {
val am = context.getSystemService(AlarmManager::class.java) ?: return
val pi = intent(context, p)
// Exact when the system allows it; otherwise within a few minutes.
val exact = Build.VERSION.SDK_INT < Build.VERSION_CODES.S || am.canScheduleExactAlarms()
runCatching {
if (exact) am.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, p.at, pi)
else am.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, p.at, pi)
}
}

private fun cancel(context: Context, p: Pending) {
val am = context.getSystemService(AlarmManager::class.java) ?: return
am.cancel(intent(context, p))
}

/** Sets the alarms of a library's next reminders, replacing the earlier ones. */
fun schedule(context: Context, library: String, notes: Collection<Note>) {
val now = nowMillis()
val next = Tasks.reminders(notes, now, now + HORIZON_MS, ALL_DAY).take(MAX).map {
Pending(it.key, library, it.noteId, it.noteTitle, it.text, it.at)
}
val old = load(context, library)
val keep = next.map { it.key }.toSet()
for (p in old) if (p.key !in keep) cancel(context, p)
for (p in next) set(context, p)
save(context, library, next)
if (next.isNotEmpty()) onScheduled?.invoke()
}

/** Sets every saved alarm again (after a reboot or an update). */
fun restore(context: Context) {
val now = nowMillis()
for (library in prefs(context).all.keys) {
val list = load(context, library).filter { it.at > now - 60_000 }
list.forEach { set(context, it) }
save(context, library, list)
}
}

/** Stops the reminders of a library (signed out, removed). */
fun clear(context: Context, library: String) {
load(context, library).forEach { cancel(context, it) }
prefs(context).edit().remove(library).apply()
}

fun mayNotify(context: Context): Boolean =
Build.VERSION.SDK_INT < 33 || ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED

/** Whether the library has reminders to come (to ask for permission). */
fun hasPending(context: Context, library: String): Boolean = load(context, library).isNotEmpty()

internal fun show(context: Context, i: Intent) {
if (!mayNotify(context)) return
ensureChannel(context)
val title = i.getStringExtra("text").orEmpty().ifEmpty { i.getStringExtra("title").orEmpty() }
val noteTitle = i.getStringExtra("title").orEmpty()
val open = Intent(context, MainActivity::class.java)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP)
.putExtra(MainActivity.EXTRA_LIBRARY, i.getStringExtra("library"))
.putExtra(MainActivity.EXTRA_NOTE, i.getStringExtra("note"))
val key = i.getStringExtra("key").orEmpty()
val tap = PendingIntent.getActivity(context, key.hashCode(), open, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
val n = NotificationCompat.Builder(context, CHANNEL)
.setSmallIcon(R.drawable.ivy_leaf)
.setContentTitle(title)
.setContentText(if (noteTitle.isNotEmpty()) L10n.s.reminderFrom(noteTitle) else null)
.setCategory(NotificationCompat.CATEGORY_REMINDER)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setAutoCancel(true)
.setContentIntent(tap)
.build()
// Checked here, where the call is: the permission can be withdrawn at any time.
if (Build.VERSION.SDK_INT >= 33 &&
ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED
) return
try {
NotificationManagerCompat.from(context).notify(key.hashCode(), n)
} catch (_: SecurityException) {
// Withdrawn between the check and the call: nothing to show.
}
}
}

/** Fires a reminder; after a reboot or an update, sets the alarms again. */
class ReminderReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
when (intent.action) {
Intent.ACTION_BOOT_COMPLETED, Intent.ACTION_MY_PACKAGE_REPLACED -> Reminders.restore(context)
else -> Reminders.show(context, intent)
}
}
}
Loading
Loading