Your Android phone and your Windows PC, working as one. Local-first, end-to-end encrypted, no account.
New photos and screenshots pop up on the PC
Bee29b98cfffe8e
diff --git a/README.md b/README.mdindex abc263a..706c288 100644--- a/README.md+++ b/README.md@@ -89,6 +89,8 @@ place and tested; the user-facing features of Phase 1 come next.on the phone, share them from any app or pick them in Nectarlink. They land in `Downloads\Nectarlink` on the PC and`Download/Nectarlink` on the phone, with progress, cancelling, and transfersthat pick up where they left off after a dropped connection.+- **New photos and screenshots** from the phone pop up on the PC with a+ preview: save them to Downloads or copy them, ready to paste.- **Media** both ways: what plays on the phone shows on the PC, in the app andin Windows' own media flyout (so the keyboard's media keys work too), andwhat plays on the PC shows in the phone's media controls, with artwork anddiff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xmlindex 2299c24..265f2c5 100644--- a/android/app/src/main/AndroidManifest.xml+++ b/android/app/src/main/AndroidManifest.xml@@ -21,6 +21,11 @@<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" /><!-- Installing its own updates from GitHub releases (the user allows it once). --><uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />+ <!-- New photos and screenshots, shown on paired PCs (asked for in the app). -->+ <uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />+ <uses-permission+ android:name="android.permission.READ_EXTERNAL_STORAGE"+ android:maxSdkVersion="32" /><!-- Names and icons of the apps whose notifications are mirrored: Androidhides other apps unless they're declared here. -->diff --git a/android/app/src/main/kotlin/app/nectarlink/android/core/Core.kt b/android/app/src/main/kotlin/app/nectarlink/android/core/Core.ktindex 9546dea..268c945 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/core/Core.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/core/Core.kt@@ -16,6 +16,7 @@ import app.nectarlink.android.files.ReceivedFilesimport app.nectarlink.android.files.TransferNotificationsimport app.nectarlink.android.Rimport app.nectarlink.android.notifications.NotificationListener+import app.nectarlink.android.photos.RecentPhotosimport app.nectarlink.core.Eventimport app.nectarlink.core.EventListenerimport app.nectarlink.core.FileToSend@@ -60,6 +61,11 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListenerprivate val platform = PhonePlatform(this.context, ringer, phoneMedia) { pc, url ->LinkNotifications.show(this.context, _state.value.nameOf(pc).orEmpty(), url)}+ private val photos = RecentPhotos(this.context) { photo ->+ notificationOps.trySend { node ->+ runCatching { node.photoTaken(photo) }.onFailure { Log.i(TAG, "a new photo wasn't announced", it) }+ }+ }/** What plays on the PCs, in Android's media controls. */val pcMedia = PcMedia(this.context) { pc, player, action, position ->@@ -127,7 +133,9 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListenerbattery.start()network.start()}+ _state.update { it.copy(photoAccess = RecentPhotos.hasAccess(context)) }started.updatePower(PowerLevel.BASIC, capabilities(NotificationListener.hasAccess(context)))+ scope.launch(Dispatchers.Main) { if (_state.value.photoAccess) photos.start() }scope.launch {for (op in notificationOps) {runCatching { op(started) }.onFailure { Log.w(TAG, "notification update failed", it) }@@ -167,10 +175,16 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListenerfun refreshNotificationAccess() {val granted = NotificationListener.hasAccess(context)val unrestricted = BackgroundAccess.isUnrestricted(context)- _state.update { it.copy(notificationAccess = granted, backgroundUnrestricted = unrestricted) }+ val photoAccess = RecentPhotos.hasAccess(context)+ val photosChanged = photoAccess != _state.value.photoAccess+ _state.update { it.copy(notificationAccess = granted, backgroundUnrestricted = unrestricted, photoAccess = photoAccess) }if (granted && NotificationListener.instance == null) {NotificationListenerService.requestRebind(NotificationListener.component(context))}+ if (photosChanged && node != null) {+ if (photoAccess) photos.start() else photos.stop()+ notificationOps.trySend { it.updatePower(PowerLevel.BASIC, capabilities(_state.value.notificationAccess)) }+ }}override fun onEvent(event: Event) {@@ -295,7 +309,9 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener/** What this phone offers PCs (docs/protocol/capabilities.md). */private fun capabilities(notificationAccess: Boolean): List<String> =- CLIPBOARD_CAPABILITIES + if (notificationAccess) NOTIFICATION_CAPABILITIES + MEDIA_CAPABILITIES else emptyList()+ CLIPBOARD_CAPABILITIES ++ (if (notificationAccess) NOTIFICATION_CAPABILITIES + MEDIA_CAPABILITIES else emptyList()) ++ (if (_state.value.photoAccess) PHOTO_CAPABILITIES else emptyList())// ---- Pairing ----@@ -432,5 +448,7 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListenerval MEDIA_CAPABILITIES = listOf("media.control")/** Accepting the PC's clipboard, and sending this one when asked. */val CLIPBOARD_CAPABILITIES = listOf("clip.write", "clip.share")+ /** With access to the phone's photos. */+ val PHOTO_CAPABILITIES = listOf("photos.read")}}diff --git a/android/app/src/main/kotlin/app/nectarlink/android/core/CoreState.kt b/android/app/src/main/kotlin/app/nectarlink/android/core/CoreState.ktindex 7c61b2e..a1d8428 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/core/CoreState.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/core/CoreState.kt@@ -62,6 +62,8 @@ data class CoreState(val ringingFrom: String? = null,/** Whether the user let Nectarlink read notifications (to mirror them). */val notificationAccess: Boolean = false,+ /** Whether the user let Nectarlink see the phone's photos (to show new ones on PCs). */+ val photoAccess: Boolean = false,/** Whether Android lets Nectarlink run unrestricted in the background. */val backgroundUnrestricted: Boolean = true,/** File transfers, newest first (running ones and the latest finished). */@@ -108,6 +110,8 @@ data class CoreState(is Event.Transfer -> copy(transfers = withTransfer(event.transfer))// Shown in Android's media controls (see media/PcMedia).is Event.MediaChanged -> this+ // PCs only: phones announce their own photos.+ is Event.PhotoAdded -> this}private fun withTransfer(transfer: Transfer): List<Transfer> {diff --git a/android/app/src/main/kotlin/app/nectarlink/android/core/PhonePlatform.kt b/android/app/src/main/kotlin/app/nectarlink/android/core/PhonePlatform.ktindex e565a0f..c99e3d7 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/core/PhonePlatform.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/core/PhonePlatform.kt@@ -11,6 +11,8 @@ import android.os.Bundleimport app.nectarlink.android.clipboard.PhoneClipboardimport app.nectarlink.android.notifications.NotificationListenerimport app.nectarlink.android.media.PhoneMedia+import app.nectarlink.android.photos.RecentPhotos+import app.nectarlink.core.FileToSendimport app.nectarlink.core.MediaActionimport app.nectarlink.core.NotificationFailureimport app.nectarlink.core.Platform@@ -42,6 +44,8 @@ internal class PhonePlatform(override fun openLink(fromId: String, url: String): Boolean = onLink(fromId, url)+ override fun openPhoto(id: String): FileToSend? = RecentPhotos.open(context, id)+override fun dismissNotification(key: String) {val listener = NotificationListener.instance ?: throw NotificationFailure.Unsupported()listener.dismiss(key)diff --git a/android/app/src/main/kotlin/app/nectarlink/android/photos/RecentPhotos.kt b/android/app/src/main/kotlin/app/nectarlink/android/photos/RecentPhotos.ktnew file mode 100644index 0000000..ad2917b--- /dev/null+++ b/android/app/src/main/kotlin/app/nectarlink/android/photos/RecentPhotos.kt@@ -0,0 +1,169 @@+// SPDX-License-Identifier: GPL-3.0-or-later+package app.nectarlink.android.photos++import android.Manifest+import android.content.ContentUris+import android.content.Context+import android.content.pm.PackageManager+import android.database.ContentObserver+import android.graphics.Bitmap+import android.net.Uri+import android.os.Build+import android.os.Handler+import android.os.Looper+import android.provider.MediaStore+import android.util.Log+import android.util.Size+import androidx.core.content.ContextCompat+import androidx.core.content.edit+import app.nectarlink.core.FileToSend+import app.nectarlink.core.Photo+import java.io.ByteArrayOutputStream++/**+ * New photos and screenshots, for PCs (docs/protocol/photos.md): watches+ * the phone's pictures while the app runs and reports each new one with a+ * small preview. A PC then asks for the photo itself by its ID.+ */+internal class RecentPhotos(context: Context, private val onPhoto: (Photo) -> Unit) {+ private val context = context.applicationContext+ private val prefs = context.getSharedPreferences("photos", Context.MODE_PRIVATE)+ private val handler = Handler(Looper.getMainLooper())+ private var observer: ContentObserver? = null+ private val check = Runnable { Thread { checkNow() }.start() }++ /** Starts watching (when allowed); only photos from now on are new. */+ fun start() {+ if (observer != null || !hasAccess(context)) return+ if (!prefs.contains(LAST_SEEN)) prefs.edit { putLong(LAST_SEEN, System.currentTimeMillis() / 1000) }+ observer = object : ContentObserver(handler) {+ // A new picture changes several rows (pending, then done): wait+ // for it to settle.+ override fun onChange(selfChange: Boolean) {+ handler.removeCallbacks(check)+ handler.postDelayed(check, SETTLE_MS)+ }+ }.also { context.contentResolver.registerContentObserver(COLLECTION, true, it) }+ }++ fun stop() {+ observer?.let { context.contentResolver.unregisterContentObserver(it) }+ observer = null+ handler.removeCallbacks(check)+ }++ @Synchronized+ private fun checkNow() {+ val lastSeen = prefs.getLong(LAST_SEEN, System.currentTimeMillis() / 1000)+ var newest = lastSeen+ val columns = arrayOf(+ MediaStore.Images.Media._ID,+ MediaStore.Images.Media.DISPLAY_NAME,+ MediaStore.Images.Media.SIZE,+ MediaStore.Images.Media.DATE_ADDED,+ MediaStore.Images.ImageColumns.DATE_TAKEN,+ MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME,+ )+ val pending = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) " AND ${MediaStore.Images.Media.IS_PENDING} = 0" else ""+ val found = runCatching {+ context.contentResolver.query(+ COLLECTION,+ columns,+ "${MediaStore.Images.Media.DATE_ADDED} > ?$pending",+ arrayOf(lastSeen.toString()),+ "${MediaStore.Images.Media.DATE_ADDED} ASC",+ )?.use { cursor ->+ buildList {+ while (cursor.moveToNext()) {+ val added = cursor.getLong(3)+ newest = maxOf(newest, added)+ val album = cursor.getString(5).orEmpty()+ add(+ Found(+ id = cursor.getLong(0),+ name = cursor.getString(1) ?: "photo.jpg",+ size = cursor.getLong(2),+ taken = cursor.getLong(4).takeIf { it > 0 }?.div(1000) ?: added,+ screenshot = album.contains("Screenshot", ignoreCase = true),+ ),+ )+ }+ }+ }.orEmpty()+ }.getOrElse {+ Log.w(TAG, "can't look for new photos", it)+ return+ }+ prefs.edit { putLong(LAST_SEEN, newest) }+ // A burst (a camera's burst mode, a downloaded album) isn't news+ // photo by photo: only the latest few.+ for (photo in found.takeLast(MAX_PER_CHECK)) {+ val thumb = preview(photo.id) ?: continue+ onPhoto(Photo(ID_PREFIX + photo.id, photo.name, photo.size.toULong(), photo.taken, photo.screenshot, thumb))+ }+ }++ private data class Found(val id: Long, val name: String, val size: Long, val taken: Long, val screenshot: Boolean)++ /** A JPEG of at most 96 KB, 512 pixels a side. */+ private fun preview(id: Long): ByteArray? = runCatching {+ val uri = ContentUris.withAppendedId(COLLECTION, id)+ val bitmap = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {+ context.contentResolver.loadThumbnail(uri, Size(PREVIEW_PX, PREVIEW_PX), null)+ } else {+ @Suppress("DEPRECATION")+ MediaStore.Images.Thumbnails.getThumbnail(context.contentResolver, id, MediaStore.Images.Thumbnails.MINI_KIND, null)+ } ?: return null+ try {+ // Lower quality until it fits.+ generateSequence(85) { it - 15 }.takeWhile { it >= 40 }+ .map { quality -> ByteArrayOutputStream().also { bitmap.compress(Bitmap.CompressFormat.JPEG, quality, it) }.toByteArray() }+ .firstOrNull { it.size <= MAX_PREVIEW_BYTES }+ } finally {+ bitmap.recycle()+ }+ }.getOrElse {+ Log.i(TAG, "no preview for a new photo", it)+ null+ }++ companion object {+ private const val TAG = "RecentPhotos"+ private const val LAST_SEEN = "lastSeen"+ private const val ID_PREFIX = "media:"+ private const val SETTLE_MS = 1500L+ private const val MAX_PER_CHECK = 3+ private const val PREVIEW_PX = 512+ private const val MAX_PREVIEW_BYTES = 96 * 1024+ private val COLLECTION: Uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI++ /** What to ask for (Android 13 split photos from other files). */+ val permissions: Array<String> =+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {+ arrayOf(Manifest.permission.READ_MEDIA_IMAGES)+ } else {+ arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE)+ }++ /**+ * Whether the app sees every new photo. Access to only some photos+ * (Android 14) isn't enough: new ones wouldn't show up.+ */+ fun hasAccess(context: Context): Boolean = permissions.all {+ ContextCompat.checkSelfPermission(context, it) == PackageManager.PERMISSION_GRANTED+ }++ /** Opens a photo a PC asked for; `null` when it's gone or not one of ours. */+ fun open(context: Context, id: String): FileToSend? {+ val mediaId = id.removePrefix(ID_PREFIX).takeIf { id.startsWith(ID_PREFIX) }?.toLongOrNull() ?: return null+ val uri = ContentUris.withAppendedId(COLLECTION, mediaId)+ val name = runCatching {+ context.contentResolver.query(uri, arrayOf(MediaStore.Images.Media.DISPLAY_NAME), null, null, null)?.use {+ if (it.moveToFirst()) it.getString(0) else null+ }+ }.getOrNull() ?: return null+ val fd = runCatching { context.contentResolver.openFileDescriptor(uri, "r") }.getOrNull() ?: return null+ return FileToSend.Fd(name = name, fd = fd.detachFd(), folder = null)+ }+ }+}diff --git a/android/app/src/main/kotlin/app/nectarlink/android/ui/MainActivity.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/MainActivity.ktindex c8ae648..f2ec942 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/ui/MainActivity.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/ui/MainActivity.kt@@ -172,6 +172,7 @@ private fun App(core: Core, state: CoreState, preferences: Preferences) {updater = (LocalContext.current.applicationContext as NectarlinkApplication).updater,onSendFiles = core::sendFiles,onSendFolder = core::sendFolder,+ onAccessChanged = core::refreshNotificationAccess,onCancelTransfer = core::cancelTransfer,modifier = modifier,)diff --git a/android/app/src/main/kotlin/app/nectarlink/android/ui/home/HomeScreen.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/home/HomeScreen.ktindex 43406fa..21ebe49 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/ui/home/HomeScreen.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/ui/home/HomeScreen.kt@@ -51,6 +51,7 @@ import app.nectarlink.android.core.BackgroundAccessimport app.nectarlink.android.core.CoreStateimport app.nectarlink.android.core.Deviceimport app.nectarlink.android.files.transferTitle+import app.nectarlink.android.photos.RecentPhotosimport app.nectarlink.android.core.isFinishedimport app.nectarlink.core.Transferimport app.nectarlink.core.TransferDirection@@ -77,6 +78,7 @@ fun HomeScreen(updater: AppUpdater,onSendFiles: (pcId: String, uris: List<Uri>) -> Unit,onSendFolder: (pcId: String, tree: Uri) -> Unit,+ onAccessChanged: () -> Unit,onCancelTransfer: (id: String) -> Unit,modifier: Modifier = Modifier,) {@@ -135,6 +137,17 @@ fun HomeScreen() { context.startActivity(NotificationListener.settingsIntent(context)) }}}+ if (state.devices.isNotEmpty() && !state.photoAccess) {+ item {+ val askPhotos = rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) {+ onAccessChanged()+ }+ SetupCard(+ stringResource(R.string.photos_title),+ stringResource(R.string.photos_off),+ ) { askPhotos.launch(RecentPhotos.permissions) }+ }+ }items(state.devices, key = { it.id }) { device -> PcCard(device, onRing, onSendFiles, onSendFolder, onPower) }if (state.transfers.isNotEmpty()) {item { TransfersCard(state, onCancelTransfer) }diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xmlindex 557443f..d3d52d5 100644--- a/android/app/src/main/res/values/strings.xml+++ b/android/app/src/main/res/values/strings.xml@@ -67,6 +67,8 @@<string name="media_previous">Previous</string><string name="action_send_files">Send files</string><string name="action_send_folder">Send a folder</string>+ <string name="photos_title">Show new photos on your PC</string>+ <string name="photos_off">Screenshots and photos you take pop up on your PC, ready to save or paste. Nectarlink needs access to your photos for that.</string><string name="transfer_too_many">That folder has too many files to send at once.</string><string name="transfers_title">Transfers</string><string name="transfer_sending">Sending to %1$s</string>diff --git a/core/nectarlink-cli/src/main.rs b/core/nectarlink-cli/src/main.rsindex 25b66d8..e3a5e31 100644--- a/core/nectarlink-cli/src/main.rs+++ b/core/nectarlink-cli/src/main.rs@@ -161,6 +161,17 @@ enum Command {},/// Open a web link on a paired device.Open { device: String, url: String },+ /// Show new photos from paired phones as this PC would, and fetch each+ /// one; stays online until Ctrl+C.+ Photos,+ /// Announce a picture as a photo just taken on this phone (use with+ /// --as-phone), then stay online to send it to PCs that ask.+ Photo {+ path: PathBuf,+ /// A JPEG preview (at most 96 KB) to show with it.+ #[arg(long)]+ preview: Option<PathBuf>,+ },/// Pretend to play a song and share it with paired devices, which can/// control it; stays online until Ctrl+C.Play {@@ -239,11 +250,24 @@ enum OnOff {Off,}+/// The picture `photo` announced, for PCs that ask for it.+static PHOTO: std::sync::OnceLock<PathBuf> = std::sync::OnceLock::new();+const PHOTO_ID: &str = "cli-photo";+/// Rings by printing to the terminal (the CLI has no speaker access).#[derive(Debug)]struct TerminalPlatform;impl Platform for TerminalPlatform {+ fn open_photo(&self, id: &str) -> std::result::Result<nectarlink_core::OutgoingFile, String> {+ let path = PHOTO.get().filter(|_| id == PHOTO_ID).ok_or("no such photo")?;+ println!("A PC asked for the photo; sending it.");+ Ok(nectarlink_core::OutgoingFile {+ name: nectarlink_core::safe_file_name(&path.to_string_lossy()),+ folder: None,+ source: nectarlink_core::FileSource::Path(path.clone()),+ })+ }fn start_ringing(&self) {println!("\x07🔔 Ringing! (stop it from the other device)");}@@ -482,7 +506,13 @@ async fn run(cli: &Cli, node: &Node) -> Result<()> {node.set_device_toggle(id, name, on)?;println!("{name} is now {}", if on { "on" } else { "off" });}- Command::Run => watch(node).await?,+ Command::Run => watch(node, false).await?,+ Command::Photos => {+ let mut offers = cli.offers.clone();+ offers.push(nectarlink_core::PHOTOS_SHOW.into());+ node.update_power(node_power(cli), offers).await;+ watch(node, true).await?;+ }Command::Power { device, action } => {let id = resolve(node, device)?;wait_until_online(node, id).await?;@@ -517,6 +547,35 @@ async fn run(cli: &Cli, node: &Node) -> Result<()> {node.update_power(node_power(cli), offers).await;play(node, title, artist, app, *length, art.as_deref()).await?;}+ Command::Photo { path, preview } => {+ if !cli.as_phone {+ bail!("photos come from phones: add --as-phone");+ }+ let thumb =+ preview.as_deref().map(std::fs::read).transpose().context("can't read the preview")?;+ let size = std::fs::metadata(path).context("can't read the picture")?.len();+ let _ = PHOTO.set(path.clone());+ let mut offers = cli.offers.clone();+ offers.push(nectarlink_core::PHOTOS_READ.into());+ node.update_power(node_power(cli), offers).await;+ // Only connected PCs hear of it.+ let first = node.paired_devices()?.first().map(|d| d.id).context("pair with a PC first")?;+ wait_until_online(node, first).await?;+ let name = nectarlink_core::safe_file_name(&path.to_string_lossy());+ let taken = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_secs() as i64;+ node.photo_taken(nectarlink_core::Photo {+ id: PHOTO_ID.into(),+ screenshot: name.to_ascii_lowercase().contains("screenshot"),+ name,+ size,+ taken,+ thumb: thumb.unwrap_or_default(),+ })+ .await+ .context("can't announce it")?;+ println!("Announced to connected PCs that show photos.");+ watch(node, false).await?;+ }Command::Notify { title, text, app, reply, silent, image } => {let image = image.as_deref().map(std::fs::read).transpose().context("can't read the picture")?;if !cli.as_phone {@@ -547,7 +606,7 @@ async fn run(cli: &Cli, node: &Node) -> Result<()> {}).await;println!("Notification sent to connected PCs (and to others when they connect).");- watch(node).await?;+ watch(node, false).await?;}}Ok(())@@ -721,7 +780,8 @@ async fn play(}}-async fn watch(node: &Node) -> Result<()> {+/// Prints events until Ctrl+C; with `fetch_photos`, also asks for each new photo.+async fn watch(node: &Node, fetch_photos: bool) -> Result<()> {println!("Online as {}. Press Ctrl+C to stop.", node.device_id());for d in node.paired_devices()? {print_device(&d);@@ -731,7 +791,17 @@ async fn watch(node: &Node) -> Result<()> {tokio::select! {_ = tokio::signal::ctrl_c() => return Ok(()),event = events.recv() => match event {- Ok(event) => print_event(node, &event),+ Ok(event) => {+ print_event(node, &event);+ if let (true, NodeEvent::PhotoAdded { device, photo }) = (fetch_photos, &event) {+ let (node, device, id) = (node.clone(), *device, photo.id.clone());+ tokio::spawn(async move {+ if let Err(e) = node.fetch_photo(device, id).await {+ println!("Couldn't fetch it: {e}");+ }+ });+ }+ }Err(RecvError::Lagged(n)) => println!("(missed {n} events)"),Err(RecvError::Closed) => return Ok(()),}@@ -789,6 +859,14 @@ fn print_event(node: &Node, event: &NodeEvent) {println!("{}: a notification went away", name(device))}NodeEvent::ClipboardReceived { device } => println!("{}: sent its clipboard", name(device)),+ NodeEvent::PhotoAdded { device, photo } => println!(+ "{}: new {} {} ({} bytes, preview {} bytes)",+ name(device),+ if photo.screenshot { "screenshot" } else { "photo" },+ photo.name,+ photo.size,+ photo.thumb.len()+ ),NodeEvent::MediaChanged { device, players } if players.is_empty() => {println!("{}: nothing playing", name(device));}diff --git a/core/nectarlink-core/src/config.rs b/core/nectarlink-core/src/config.rsindex 4902e7c..d572ea1 100644--- a/core/nectarlink-core/src/config.rs+++ b/core/nectarlink-core/src/config.rs@@ -116,6 +116,13 @@ pub trait Platform: Send + Sync + 'static {Err("this device doesn't open links".into())}+ /// Open a photo this phone announced (with+ /// [`Node::photo_taken`](crate::Node::photo_taken)), for sending it to a+ /// PC that asked. `Err` (a reason for logs) when it's gone.+ fn open_photo(&self, _id: &str) -> Result<crate::OutgoingFile, String> {+ Err("this device doesn't share photos".into())+ }+/// Run a command on one of this device's media players (a paired device/// asked); `position` is set for [`MediaAction::Seek`].fn media_command(diff --git a/core/nectarlink-core/src/events.rs b/core/nectarlink-core/src/events.rsindex fb4f20f..1e908b0 100644--- a/core/nectarlink-core/src/events.rs+++ b/core/nectarlink-core/src/events.rs@@ -128,4 +128,10 @@ pub enum NodeEvent {device: DeviceId,players: Vec<MediaPlayer>,},+ /// A phone took a photo or screenshot (with a preview); fetch it with+ /// [`Node::fetch_photo`](crate::Node::fetch_photo).+ PhotoAdded {+ device: DeviceId,+ photo: crate::Photo,+ },}diff --git a/core/nectarlink-core/src/lib.rs b/core/nectarlink-core/src/lib.rsindex c7d790b..4f1ede1 100644--- a/core/nectarlink-core/src/lib.rs+++ b/core/nectarlink-core/src/lib.rs@@ -17,6 +17,7 @@ mod media;mod node;mod notifications;mod pairing;+mod photos;mod session;mod store;mod transfer;@@ -37,7 +38,8 @@ pub use nectarlink_protocol::{DeviceId,messages::{Battery, CLIP_MAX_BYTES, DeviceInfo, DeviceKind, MediaPlayer, Notification, NotificationAction,- PowerLevel,+ PhotoNew as Photo, PowerLevel,+ photos::{MAX_THUMB_BYTES as PHOTO_MAX_THUMB_BYTES, READ as PHOTOS_READ, SHOW as PHOTOS_SHOW},},pairing::PairingUri,};diff --git a/core/nectarlink-core/src/node.rs b/core/nectarlink-core/src/node.rsindex d8ad1db..99c54aa 100644--- a/core/nectarlink-core/src/node.rs+++ b/core/nectarlink-core/src/node.rs@@ -115,6 +115,8 @@ pub(crate) struct Shared {pub notifications: Feed,/// This device's media players (docs/protocol/media.md).pub players: crate::media::Players,+ /// Photos this phone announced lately (docs/protocol/photos.md).+ pub(crate) photos: crate::photos::Recent,pub data_dir: std::path::PathBuf,/// Where received files go.pub downloads_dir: std::path::PathBuf,@@ -603,6 +605,7 @@ impl Node {memory,notifications: Feed::default(),players: Default::default(),+ photos: Default::default(),data_dir: config.data_dir.clone(),downloads_dir: config.downloads_dir.clone().unwrap_or_else(|| config.data_dir.join("received")),transfers: Mutex::new(HashMap::new()),@@ -914,6 +917,22 @@ impl Node {crate::actions::open_link(&self.shared, &session, url).await}+ // ---- Photos (docs/protocol/photos.md) ----++ /// A photo or screenshot just appeared on this phone; announced to every+ /// connected PC the user allows. PCs then ask for it through+ /// [`Platform::open_photo`](crate::Platform::open_photo).+ pub async fn photo_taken(&self, photo: crate::Photo) -> Result<()> {+ self.shared.photo_taken(photo).await+ }++ /// Asks a phone for a photo it announced; returns the ID of the+ /// transfer that brings it (reported like any other).+ pub async fn fetch_photo(&self, peer: DeviceId, id: String) -> Result<String> {+ let session = self.connected(&peer)?;+ crate::photos::fetch(&self.shared, &session, id).await+ }+// ---- Media (docs/protocol/media.md) ----/// This device's media players changed (most relevant first); sent todiff --git a/core/nectarlink-core/src/photos.rs b/core/nectarlink-core/src/photos.rsnew file mode 100644index 0000000..7e9678d--- /dev/null+++ b/core/nectarlink-core/src/photos.rs@@ -0,0 +1,154 @@+// SPDX-License-Identifier: MPL-2.0+//! Recent photos (docs/protocol/photos.md): a phone announces each new+//! photo or screenshot to PCs with a preview, and sends the photo itself+//! (as a files transfer) when a PC asks for it.++use std::{collections::VecDeque, sync::Arc};++use nectarlink_protocol::{+ DeviceId, Envelope, ErrorCode,+ messages::{PhotoGet, PhotoNew, PhotoSending, photos, types},+};++use crate::{Error, Result, events::NodeEvent, node::Shared, session::Session};++/// The device toggle that allows recent photos for a device.+pub(crate) const TOGGLE: &str = "photos";+/// A PC can ask for this many of the latest announced photos.+const REMEMBERED: usize = 50;++/// The photos this phone announced lately: the only ones a PC may ask for.+#[derive(Debug, Default)]+pub(crate) struct Recent(std::sync::Mutex<VecDeque<String>>);++impl Recent {+ fn add(&self, id: &str) {+ let mut ids = self.0.lock().unwrap_or_else(|e| e.into_inner());+ ids.retain(|known| known != id);+ ids.push_back(id.to_owned());+ while ids.len() > REMEMBERED {+ ids.pop_front();+ }+ }++ fn contains(&self, id: &str) -> bool {+ self.0.lock().unwrap_or_else(|e| e.into_inner()).iter().any(|known| known == id)+ }+}++impl Shared {+ /// PCs that show photos and are allowed them.+ fn photo_targets(&self) -> Vec<Arc<Session>> {+ self.live_sessions()+ .into_iter()+ .filter(|s| {+ self.is_desktop(&s.peer)+ && self.toggle_on(&s.peer, TOGGLE)+ && self+ .store+ .get_peer(&s.peer)+ .ok()+ .flatten()+ .is_some_and(|p| p.caps.contains(photos::SHOW))+ })+ .collect()+ }++ pub(crate) async fn photo_taken(&self, photo: PhotoNew) -> Result<()> {+ if !photo.is_valid() {+ return Err(if photo.thumb.len() > photos::MAX_THUMB_BYTES {+ Error::TooLarge+ } else {+ Error::Protocol("invalid photo".into())+ });+ }+ self.photos.add(&photo.id);+ let env = Envelope::new(types::PHOTOS_NEW, &photo)?;+ for session in self.photo_targets() {+ let _ = session.send(env.clone()).await;+ }+ Ok(())+ }+}++/// Asks a phone for a photo it announced; returns the transfer that brings it.+pub(crate) async fn fetch(shared: &Shared, session: &Session, id: String) -> Result<String> {+ if !shared.toggle_on(&session.peer, TOGGLE) {+ return Err(Error::Denied);+ }+ let env = Envelope::new(types::PHOTOS_GET, &PhotoGet { id })?;+ let reply = session.request(env, crate::session::REQUEST_TIMEOUT).await?;+ let PhotoSending { transfer } = reply.expect_body(types::PHOTOS_SENDING)?;+ Ok(transfer)+}++/// Handles `photos.*`. Returns false for other types.+pub(crate) async fn handle(shared: &Arc<Shared>, session: &Arc<Session>, env: &Envelope) -> Result<bool> {+ let peer = session.peer;+ match env.t.as_str() {+ types::PHOTOS_NEW => {+ let photo: PhotoNew = env.body()?;+ let shows = shared.local_capabilities().iter().any(|c| c == photos::SHOW);+ if shows && photo.is_valid() && shared.toggle_on(&peer, TOGGLE) {+ shared.emit(NodeEvent::PhotoAdded { device: peer, photo });+ }+ Ok(true)+ }+ types::PHOTOS_GET => {+ let PhotoGet { id } = env.body()?;+ let reply = match send_photo(shared, peer, &id).await {+ Ok(transfer) => Envelope::new(types::PHOTOS_SENDING, &PhotoSending { transfer })?,+ Err(Error::Denied) => {+ Envelope::error(ErrorCode::Denied, "photos or files are off for this device")+ }+ Err(Error::NotFound) => Envelope::error(ErrorCode::NotFound, "no such photo"),+ Err(e) => {+ tracing::warn!(error = %e, "can't send a photo");+ Envelope::error(ErrorCode::Internal, "can't send it")+ }+ };+ session.send(reply.reply_to(env.id)).await?;+ Ok(true)+ }+ _ => Ok(false),+ }+}++async fn send_photo(shared: &Arc<Shared>, peer: DeviceId, id: &str) -> Result<String> {+ if !shared.toggle_on(&peer, TOGGLE) {+ return Err(Error::Denied);+ }+ if !shared.photos.contains(id) {+ return Err(Error::NotFound);+ }+ let platform = shared.platform.clone();+ let owned = id.to_owned();+ let file = tokio::task::spawn_blocking(move || platform.open_photo(&owned))+ .await+ .map_err(|e| Error::Internal(e.to_string()))?+ .map_err(|reason| {+ tracing::info!(reason, "an announced photo can't be opened");+ Error::NotFound+ })?;+ crate::transfer::send(shared, peer, vec![file]).await+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn only_the_latest_are_remembered() {+ let recent = Recent::default();+ for i in 0..REMEMBERED + 5 {+ recent.add(&i.to_string());+ }+ assert!(!recent.contains("0") && !recent.contains("4"));+ assert!(recent.contains("5") && recent.contains(&(REMEMBERED + 4).to_string()));+ // Announcing one again moves it to the end.+ recent.add("5");+ recent.add("new");+ assert!(recent.contains("5"));+ assert!(!recent.contains("6"));+ }+}diff --git a/core/nectarlink-core/src/session.rs b/core/nectarlink-core/src/session.rsindex e31d970..4e6993d 100644--- a/core/nectarlink-core/src/session.rs+++ b/core/nectarlink-core/src/session.rs@@ -350,6 +350,7 @@ async fn handle(shared: &Arc<Shared>, session: &Arc<Session>, env: Envelope) ->t if (t.starts_with("pc.") || t.starts_with("link."))&& crate::actions::handle(shared, session, &env).await? => {}t if t.starts_with("clip.") && crate::clipboard::handle(shared, session, &env).await? => {}+ t if t.starts_with("photos.") && crate::photos::handle(shared, session, &env).await? => {}other => {if env.id.is_some() {let reply = Envelope::error(ErrorCode::Unsupported, format!("unknown message type {other}"));diff --git a/core/nectarlink-core/tests/two_devices.rs b/core/nectarlink-core/tests/two_devices.rsindex 3f35b1b..19b4fd8 100644--- a/core/nectarlink-core/tests/two_devices.rs+++ b/core/nectarlink-core/tests/two_devices.rs@@ -30,6 +30,8 @@ struct RecordingPlatform {media: Mutex<Vec<(String, MediaAction, Option<u64>)>>,power: Mutex<Vec<PowerAction>>,links: Mutex<Vec<String>>,+ /// Photos `open_photo` finds, by ID.+ photos: Mutex<std::collections::HashMap<String, std::path::PathBuf>>,}impl Platform for RecordingPlatform {@@ -71,6 +73,11 @@ impl Platform for RecordingPlatform {self.links.lock().unwrap().push(url.to_owned());Ok(())}+ fn open_photo(&self, id: &str) -> Result<OutgoingFile, String> {+ let path = self.photos.lock().unwrap().get(id).cloned().ok_or("gone")?;+ let name = path.file_name().unwrap().to_string_lossy().into_owned();+ Ok(OutgoingFile { name, folder: None, source: FileSource::Path(path) })+ }fn media_command(&self,player: &str,@@ -936,6 +943,48 @@ async fn folders_arrive_with_their_layout() {);}+#[tokio::test(flavor = "multi_thread")]+async fn new_photos_reach_the_pc_and_come_when_asked() {+ let mut pc = device_with("Desktop", DeviceKind::Desktop, &[nectarlink_core::PHOTOS_SHOW]).await;+ let mut phone = device_with("Pixel", DeviceKind::Phone, &[nectarlink_core::PHOTOS_READ]).await;+ pair_qr(&mut pc, &mut phone).await;+ let (pc_id, phone_id) = (pc.node.device_id(), phone.node.device_id());+ let shot = phone.dir.path().join("Screenshot_1.png");+ let pixels = data(300_000, 7);+ std::fs::write(&shot, &pixels).unwrap();+ phone.platform.photos.lock().unwrap().insert("media:1".into(), shot);+ let photo = nectarlink_core::Photo {+ id: "media:1".into(),+ name: "Screenshot_1.png".into(),+ size: pixels.len() as u64,+ taken: 1_790_000_000,+ screenshot: true,+ thumb: vec![0xff, 0xd8, 0xff],+ };++ phone.node.photo_taken(photo.clone()).await.unwrap();+ let got = wait_for(&mut pc, "the photo", |e| match e {+ NodeEvent::PhotoAdded { device, photo } if *device == phone_id => Some(photo.clone()),+ _ => None,+ })+ .await;+ assert_eq!(got, photo);++ // The PC asks for it: it comes as a transfer.+ let id = with_timeout("fetch", pc.node.fetch_photo(phone_id, "media:1".into())).await.unwrap();+ let saved = wait_transfer(&mut pc, &id, "the photo", saved).await;+ assert_eq!(std::fs::read(&saved[0]).unwrap(), pixels);++ // Only announced photos can be asked for.+ assert!(matches!(pc.node.fetch_photo(phone_id, "media:2".into()).await, Err(Error::NotFound)));+ // The phone's user turned photos off for this PC: nothing more comes.+ phone.node.set_device_toggle(pc_id, "photos", false).unwrap();+ assert!(matches!(pc.node.fetch_photo(phone_id, "media:1".into()).await, Err(Error::Denied)));+ // An oversized preview isn't sent.+ let big = nectarlink_core::Photo { thumb: vec![0; nectarlink_core::PHOTO_MAX_THUMB_BYTES + 1], ..photo };+ assert!(matches!(phone.node.photo_taken(big).await, Err(Error::TooLarge)));+}+#[tokio::test(flavor = "multi_thread")]async fn files_need_the_toggle_and_can_be_cancelled() {let mut pc = device("Desktop", DeviceKind::Desktop).await;diff --git a/core/nectarlink-ffi/src/lib.rs b/core/nectarlink-ffi/src/lib.rsindex f99bd1b..ea2ed9a 100644--- a/core/nectarlink-ffi/src/lib.rs+++ b/core/nectarlink-ffi/src/lib.rs@@ -424,6 +424,33 @@ pub enum Event {id: String,players: Vec<MediaPlayer>,},+ /// A paired phone took a photo (PCs only; phones announce theirs).+ PhotoAdded {+ id: String,+ photo_id: String,+ },+}++/// A photo or screenshot that just appeared on this phone+/// (docs/protocol/photos.md).+#[derive(Clone, PartialEq, Eq, uniffi::Record)]+pub struct Photo {+ /// This app's ID for it (a PC asks for it by this ID).+ pub id: String,+ pub name: String,+ pub size: u64,+ /// When it was taken, in Unix seconds.+ pub taken: i64,+ pub screenshot: bool,+ /// A JPEG preview of at most 96 KB, at most 512 pixels a side.+ pub thumb: Vec<u8>,+}++/// Never prints the name or picture (protocol v0 §11).+impl std::fmt::Debug for Photo {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("Photo").field("id", &self.id).finish_non_exhaustive()+ }}#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error, uniffi::Error)]@@ -790,6 +817,9 @@ impl From<NodeEvent> for Event {id: device.to_string(),players: players.into_iter().map(Into::into).collect(),},+ NodeEvent::PhotoAdded { device, photo } => {+ Event::PhotoAdded { id: device.to_string(), photo_id: photo.id }+ }}}}@@ -893,6 +923,9 @@ pub trait Platform: Send + Sync {/// A paired PC sent a web link (http or https, checked) to open./// False if it couldn't be shown.fn open_link(&self, from_id: String, url: String) -> bool;+ /// A PC asked for a photo announced with `photo_taken`: open it, or+ /// `null` when it's gone.+ fn open_photo(&self, id: String) -> Option<FileToSend>;}/// Encrypts the device key at rest (Android: a Keystore key).@@ -955,6 +988,10 @@ impl core::Platform for PlatformAdapter {Err("the clipboard rejected it".into())}}+ fn open_photo(&self, id: &str) -> Result<core::OutgoingFile, String> {+ let file = self.0.open_photo(id.to_owned()).ok_or("it's gone")?;+ file_to_send(file).map_err(|e| e.to_string())+ }}struct KeyProtectorAdapter(Arc<dyn KeyProtector>);@@ -1250,6 +1287,21 @@ impl NectarlinkNode {self.run(async move { Ok(node.open_link(id, url).await?) }).await}+ /// A photo or screenshot just appeared on this phone: tells the PCs+ /// that show photos (and are allowed them).+ pub async fn photo_taken(&self, photo: Photo) -> Result<()> {+ let node = self.node.clone();+ let photo = core::Photo {+ id: photo.id,+ name: photo.name,+ size: photo.size,+ taken: photo.taken,+ screenshot: photo.screenshot,+ thumb: photo.thumb,+ };+ self.run(async move { Ok(node.photo_taken(photo).await?) }).await+ }+/// Reconnects to PCs that aren't connected and syncs connected ones.pub async fn refresh(&self) {let node = self.node.clone();diff --git a/core/nectarlink-protocol/src/messages.rs b/core/nectarlink-protocol/src/messages.rsindex 2287f21..134d946 100644--- a/core/nectarlink-protocol/src/messages.rs+++ b/core/nectarlink-protocol/src/messages.rs@@ -40,6 +40,9 @@ pub mod types {pub const MEDIA_COMMAND: &str = "media.command";pub const PC_POWER: &str = "pc.power";pub const LINK_OPEN: &str = "link.open";+ pub const PHOTOS_NEW: &str = "photos.new";+ pub const PHOTOS_GET: &str = "photos.get";+ pub const PHOTOS_SENDING: &str = "photos.sending";}/// What kind of device this is.@@ -453,6 +456,74 @@ pub struct PcPower {/// The longest link sent, in bytes.pub const LINK_MAX_BYTES: usize = 4096;+// ---- Photos (docs/protocol/photos.md) ----++pub mod photos {+ /// Offered by phones that announce new photos (and can read them).+ pub const READ: &str = "photos.read";+ /// Offered by PCs that show announced photos.+ pub const SHOW: &str = "photos.show";+ /// A photo's ID: at most this many bytes.+ pub const MAX_ID_BYTES: usize = 64;+ /// A preview: a JPEG of at most this many bytes.+ pub const MAX_THUMB_BYTES: usize = 96 * 1024;+}++/// Body of `photos.new`: a photo or screenshot just appeared on the phone.+#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct PhotoNew {+ /// The phone's ID for it; asks for the photo with `photos.get`.+ pub id: String,+ pub name: String,+ pub size: u64,+ /// When it was taken, in Unix seconds.+ pub taken: i64,+ /// A screenshot rather than a photo.+ #[serde(default)]+ pub screenshot: bool,+ /// A small JPEG preview.+ #[serde(with = "serde_bytes")]+ pub thumb: Vec<u8>,+}++/// Never prints the name or picture (protocol v0 §11).+impl std::fmt::Debug for PhotoNew {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("PhotoNew")+ .field("id", &self.id)+ .field("size", &self.size)+ .field("screenshot", &self.screenshot)+ .field("thumb", &self.thumb.len())+ .finish_non_exhaustive()+ }+}++impl PhotoNew {+ pub fn is_valid(&self) -> bool {+ is_valid_photo_id(&self.id)+ && is_valid_file_name(&self.name)+ && self.thumb.len() <= photos::MAX_THUMB_BYTES+ }+}++/// Whether a photo ID is 1–64 printable ASCII characters.+pub fn is_valid_photo_id(id: &str) -> bool {+ (1..=photos::MAX_ID_BYTES).contains(&id.len()) && id.bytes().all(|b| b.is_ascii_graphic())+}++/// Body of `photos.get`: send this photo.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct PhotoGet {+ pub id: String,+}++/// Body of `photos.sending`, the answer to `photos.get`: the files+/// transfer that brings it.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct PhotoSending {+ pub transfer: String,+}+/// Body of `link.open`.#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct LinkOpen {@@ -773,6 +844,24 @@ mod tests {assert!(!format!("{:?}", offer("Secret")).contains("Secret"));}+ #[test]+ fn photos_are_validated() {+ let photo = PhotoNew {+ id: "content:42".into(),+ name: "Screenshot_20261006.png".into(),+ size: 1000,+ taken: 1_790_000_000,+ screenshot: true,+ thumb: vec![0xff, 0xd8],+ };+ assert!(photo.is_valid());+ assert!(!format!("{photo:?}").contains("Screenshot_"));+ assert!(!PhotoNew { id: String::new(), ..photo.clone() }.is_valid());+ assert!(!PhotoNew { id: "a b".into(), ..photo.clone() }.is_valid());+ assert!(!PhotoNew { name: "../x.png".into(), ..photo.clone() }.is_valid());+ assert!(!PhotoNew { thumb: vec![0; photos::MAX_THUMB_BYTES + 1], ..photo }.is_valid());+ }+#[test]fn power_level_wire_names() {let env = Envelope::new("x", &PowerLevel::NotApplicable).unwrap();diff --git a/desktop/app/src/core_host.rs b/desktop/app/src/core_host.rsindex 1ad08e5..3b9390a 100644--- a/desktop/app/src/core_host.rs+++ b/desktop/app/src/core_host.rs@@ -95,7 +95,8 @@ async fn run(data_dir: PathBuf, platform: Arc<dyn Platform>) {let mut config = NodeConfig::new(&data_dir, this_device(), env!("CARGO_PKG_VERSION"));config.downloads_dir = Some(downloads_dir());// This PC's own players, for phones (crate::win::media_sessions).- config.capabilities = vec!["media.control".into(), "pc.power".into()];+ config.capabilities =+ vec!["media.control".into(), "pc.power".into(), nectarlink_core::PHOTOS_SHOW.into()];let node = match Node::start(config, platform).await {Ok(node) => node,Err(e) => {@@ -141,6 +142,7 @@ async fn run(data_dir: PathBuf, platform: Arc<dyn Platform>) {crate::media::on_event(&event);crate::notifications::update_toasts(&event);crate::clipboard::on_event(&event);+ crate::photos::on_event(&event);crate::transfers::on_event(&event);crate::send_to::on_event(&event);crate::battery::on_event(&event);diff --git a/desktop/app/src/main.rs b/desktop/app/src/main.rsindex 417011e..bbee16f 100644--- a/desktop/app/src/main.rs+++ b/desktop/app/src/main.rs@@ -22,6 +22,7 @@ mod media;mod notification_store;mod notifications;mod palette;+mod photos;mod qr;mod send_to;mod settings;diff --git a/desktop/app/src/notifications.rs b/desktop/app/src/notifications.rsindex 181dd99..76f6861 100644--- a/desktop/app/src/notifications.rs+++ b/desktop/app/src/notifications.rs@@ -28,7 +28,7 @@ fn toasted<T>(f: impl FnOnce(&mut HashMap<DeviceId, HashSet<String>>) -> T) -> T/// Pictures from notifications, kept for a couple of days (history lasts one).const KEEP_IMAGES: std::time::Duration = std::time::Duration::from_secs(2 * 24 * 3600);-fn images_dir() -> std::path::PathBuf {+pub(crate) fn images_dir() -> std::path::PathBuf {core_host::host().data_dir.join("cache").join("images")}@@ -210,6 +210,14 @@ pub fn on_toast(event: ToastEvent) {return crate::bridge::app::install_update_in_background();}ToastEvent::Dismissed { device, .. } if device == crate::updater::TOAST_GROUP => return,+ // New photos: open, save or copy one.+ ToastEvent::Opened { device, key } if device == crate::photos::TOAST_GROUP => {+ return crate::photos::on_toast(key, None);+ }+ ToastEvent::Action { device, key, action } if device == crate::photos::TOAST_GROUP => {+ return crate::photos::on_toast(key, Some(action));+ }+ ToastEvent::Dismissed { device, .. } if device == crate::photos::TOAST_GROUP => return,ToastEvent::Dismissed { device, .. } | ToastEvent::Action { device, .. }if device == crate::battery::TOAST_GROUP =>{diff --git a/desktop/app/src/photos.rs b/desktop/app/src/photos.rsnew file mode 100644index 0000000..d13bcc4--- /dev/null+++ b/desktop/app/src/photos.rs@@ -0,0 +1,202 @@+// SPDX-License-Identifier: GPL-3.0-or-later+//! New photos from a phone (docs/protocol/photos.md): a Windows+//! notification with the preview, to open the photo, save it, or copy it.+//! The photo itself comes as a files transfer when the user asks.++use std::{+ collections::HashMap,+ path::{Path, PathBuf},+ sync::Mutex,+ time::{Duration, Instant},+};++use nectarlink_core::{DeviceId, Direction, Error, NodeEvent, Photo, Transfer, TransferState};++use crate::{+ bridge::app::{describe, show_message},+ core_host,+ win::toast::{self, Toast},+};++/// The toast "device" for photos; their key is `<device ID> <photo ID>`.+pub const TOAST_GROUP: &str = "photos";+pub const ACTION_SAVE: &str = "save";+pub const ACTION_COPY: &str = "copy";++/// What the user wants done with a photo once it's here.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum Intent {+ /// Kept in Downloads (the usual "saved" notification says so).+ Save,+ /// Opened in its app.+ Open,+ /// Put on the clipboard; not kept.+ Copy,+}++#[derive(Debug, Default)]+struct State {+ /// Transfers bringing photos the user asked for.+ pending: HashMap<String, Intent>,+ /// Incoming transfers that finished lately, in case one finishes+ /// before the phone's answer says which it was.+ finished: HashMap<String, (Instant, Vec<PathBuf>)>,+}++static STATE: Mutex<Option<State>> = Mutex::new(None);+const KEEP_FINISHED: Duration = Duration::from_secs(60);++fn state<T>(f: impl FnOnce(&mut State) -> T) -> T {+ f(STATE.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert_default())+}++pub fn on_event(event: &NodeEvent) {+ match event {+ NodeEvent::PhotoAdded { device, photo } => show(*device, photo),+ NodeEvent::Transfer(t) if t.direction == Direction::Incoming => finished(t),+ _ => {}+ }+}++/// Whether this transfer brings a photo the user asked to open or copy,+/// so the usual "saved" notification isn't wanted.+pub fn handles(transfer_id: &str) -> bool {+ state(|s| s.pending.get(transfer_id).is_some_and(|intent| *intent != Intent::Save))+}++fn show(device: DeviceId, photo: &Photo) {+ tracing::debug!(+ screenshot = photo.screenshot,+ preview = !photo.thumb.is_empty(),+ "a phone has a new photo"+ );+ let preview = save_preview(device, photo);+ let name = core_host::host().hub.read(|s| s.name_of(&device)).unwrap_or_else(|| "your phone".into());+ toast::show(Toast {+ device: TOAST_GROUP.into(),+ key: format!("{device} {}", photo.id),+ title: if photo.screenshot { "New screenshot".into() } else { "New photo".into() },+ body: format!("From {name}"),+ attribution: "Nectarlink".into(),+ icon: None,+ image: preview,+ actions: vec![(ACTION_SAVE.into(), "Save".into()), (ACTION_COPY.into(), "Copy".into())],+ reply: None,+ silent: true,+ progress: None,+ });+}++/// The preview as a file, for the notification.+fn save_preview(device: DeviceId, photo: &Photo) -> Option<PathBuf> {+ if photo.thumb.is_empty() {+ return None;+ }+ let dir = crate::notifications::images_dir();+ let path = dir.join(format!("photo-{:016x}.jpg", fingerprint(&format!("{device} {}", photo.id))));+ let written = std::fs::create_dir_all(&dir).and_then(|()| std::fs::write(&path, &photo.thumb));+ match written {+ Ok(()) => Some(path),+ Err(e) => {+ tracing::warn!(error = %e, "can't keep a photo preview");+ None+ }+ }+}++fn fingerprint(text: &str) -> u64 {+ text.bytes().fold(0xcbf2_9ce4_8422_2325, |hash, b| (hash ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3))+}++/// The user clicked the notification (`action` None) or one of its buttons.+pub fn on_toast(key: &str, action: Option<&str>) {+ let Some((device, photo_id)) = key.split_once(' ') else { return };+ let Ok(device) = device.parse::<DeviceId>() else { return };+ let intent = match action {+ None => Intent::Open,+ Some(ACTION_SAVE) => Intent::Save,+ Some(ACTION_COPY) => Intent::Copy,+ Some(_) => return,+ };+ let Some(node) = core_host::node() else { return };+ let photo_id = photo_id.to_owned();+ core_host::spawn(async move {+ match node.fetch_photo(device, photo_id).await {+ Ok(transfer) => asked(transfer, intent),+ Err(Error::NotFound) => show_message("That photo isn't on the phone anymore."),+ Err(Error::Denied) => show_message("The phone doesn't share photos or files with this PC."),+ Err(e) => show_message(describe(&e)),+ }+ });+}++fn asked(transfer: String, intent: Intent) {+ let done = state(|s| {+ let now = Instant::now();+ s.finished.retain(|_, (at, _)| now.duration_since(*at) < KEEP_FINISHED);+ match s.finished.remove(&transfer) {+ Some((_, saved)) => Some(saved),+ None => {+ s.pending.insert(transfer, intent);+ None+ }+ }+ });+ // Already here: the usual notification came first.+ if let Some(saved) = done {+ if let (true, Some(first)) = (intent != Intent::Save, saved.first()) {+ toast::remove(crate::transfers::TOAST_GROUP, &first.to_string_lossy());+ }+ deliver(intent, &saved);+ }+}++fn finished(t: &Transfer) {+ let saved = match &t.state {+ TransferState::Done { saved } => saved.clone(),+ TransferState::Failed(_) | TransferState::Cancelled => {+ state(|s| s.pending.remove(&t.id));+ return;+ }+ _ => return,+ };+ let intent = state(|s| match s.pending.remove(&t.id) {+ Some(intent) => Some(intent),+ None => {+ s.finished.insert(t.id.clone(), (Instant::now(), saved.clone()));+ None+ }+ });+ if let Some(intent) = intent {+ deliver(intent, &saved);+ }+}++fn deliver(intent: Intent, saved: &[PathBuf]) {+ let Some(path) = saved.first() else { return };+ match intent {+ Intent::Save => {}+ Intent::Open => crate::transfers::open(path),+ Intent::Copy => copy(path),+ }+}++fn copy(path: &Path) {+ let mime = match path.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase).as_deref() {+ Some("png") => "image/png",+ _ => "image/jpeg",+ };+ let copied = std::fs::read(path)+ .map_err(|e| e.to_string())+ .and_then(|bytes| crate::win::clipboard::write_image(mime, &bytes));+ match copied {+ // Only wanted on the clipboard.+ Ok(()) => {+ let _ = std::fs::remove_file(path);+ }+ Err(reason) => {+ tracing::warn!(reason, "can't copy a photo");+ show_message("The photo couldn't be copied. It's in Downloads\\Nectarlink.");+ }+ }+}diff --git a/desktop/app/src/state.rs b/desktop/app/src/state.rsindex 6d02469..03d749e 100644--- a/desktop/app/src/state.rs+++ b/desktop/app/src/state.rs@@ -380,8 +380,9 @@ impl AppState {let gone = self.notifications.remove(at);Changes::NOTIFICATIONS | self.remember(vec![gone])}- // Feedback only (see crate::clipboard); nothing to keep.- NodeEvent::ClipboardReceived { .. } => Changes::NONE,+ // Feedback (crate::clipboard) and notifications (crate::photos)+ // only; nothing to keep.+ NodeEvent::ClipboardReceived { .. } | NodeEvent::PhotoAdded { .. } => Changes::NONE,NodeEvent::Transfer(transfer) => self.update_transfer(transfer.clone(), Instant::now()),// With artwork saved first (see crate::media).NodeEvent::MediaChanged { .. } => Changes::NONE,diff --git a/desktop/app/src/transfers.rs b/desktop/app/src/transfers.rsindex d9512ef..7db8e71 100644--- a/desktop/app/src/transfers.rs+++ b/desktop/app/src/transfers.rs@@ -72,7 +72,8 @@ pub fn show_in_folder(path: &Path) {/// A Windows notification when files from a phone are saved.pub fn on_event(event: &NodeEvent) {let NodeEvent::Transfer(t) = event else { return };- if t.direction != Direction::Incoming {+ // Photos the user asked to open or copy say nothing about being saved.+ if t.direction != Direction::Incoming || crate::photos::handles(&t.id) {return;}let TransferState::Done { saved } = &t.state else { return };diff --git a/docs/protocol/capabilities.md b/docs/protocol/capabilities.mdindex 1a4b51e..958ad50 100644--- a/docs/protocol/capabilities.md+++ b/docs/protocol/capabilities.md@@ -40,7 +40,7 @@ capability is missing.| `clip.write` | Accepts clipboard content from the PC ([clipboard service](clipboard.md)) | app update || `clip.share` | Sends the clipboard when the user taps "Send" | app update || `clip.read.auto` | Sends clipboard changes automatically, in the background | Elevated |-| `photos.read` | Lists and sends recent photos and screenshots | photos permission |+| `photos.read` | Announces new photos and screenshots and sends them on request ([photos](photos.md)) | photos permission || `mirror.capture` | Streams its screen (with the system's capture prompt at Basic) | app update || `mirror.input` | Accepts touch, key and scroll input while mirrored | Assist || `mirror.virtual_display` | Runs apps on a separate virtual display (app windows) | Elevated |@@ -53,6 +53,7 @@ capability is missing.| ID | Meaning | Unlocked by ||---|---|---|| `pc.power` | Locks or sleeps on request ([actions](actions.md)) | app update |+| `photos.show` | Shows a phone's new photos ([photos](photos.md)) | app update || `files.browse` | Lets a paired phone browse and fetch its files | app update || `input.inject` | Accepts pointer and keyboard input (touchpad, air mouse, voice typing) | app update || `deck.actions` | Runs Deck actions | app update |diff --git a/docs/protocol/photos.md b/docs/protocol/photos.mdnew file mode 100644index 0000000..52cb839--- /dev/null+++ b/docs/protocol/photos.md@@ -0,0 +1,60 @@+# Photos service (protocol v0)++> Status: **draft.** Builds on [protocol v0](v0.md) and the+> [files service](files.md); breaking changes are allowed until v1.+> License: CC BY 4.0.++A phone tells its PCs about each photo or screenshot it takes, with a small+preview, so the PC can offer it right away. The photo itself comes only+when the PC asks, as an ordinary files transfer.++## 1. Capabilities++| ID | Offered by | Meaning |+|---|---|---|+| `photos.read` | phone | Announces new photos and sends them on request (needs the phone's photos permission) |+| `photos.show` | PC | Shows announced photos |++A phone announces photos only to PCs that offer `photos.show`, and only+while both devices allow it (the `photos` device toggle, on by default, on+each side).++## 2. Messages++On the control stream.++```+t = "photos.new" b = {+ id: text, // The phone's ID for it: 1–64 printable ASCII characters+ name: text, // A file name, as in files.offer+ size: uint, // Bytes+ taken: int, // Unix seconds+ screenshot: bool, // Optional, false when missing+ thumb: bytes, // A JPEG preview: at most 96 KiB, at most 512 pixels a side+}+t = "photos.get" id = n b = { id: text }+t = "photos.sending" re = n b = { transfer: text }+```++### 2.1 `photos.new`++Sent once per new photo, to the PCs connected at the time; a PC that+connects later doesn't hear about it. It isn't answered. Phones **SHOULD**+leave out bursts (a camera's burst mode, a downloaded album) beyond the+latest few. A PC drops announcements that break the rules above.++### 2.2 `photos.get`++Asks for an announced photo. The phone starts sending it as a files+transfer ([files](files.md) §2) and answers with that transfer's `id`; the+PC finds the file there when the transfer is done.++A phone keeps at least the 50 latest announced IDs and sends only photos+it announced. Errors: `NOT_FOUND` when the ID isn't one of them or the+photo is gone; `DENIED` when photos or files are off for the PC.++## 3. Privacy++- Nothing is sent before the user gives the phone app access to photos,+ and only photos taken from then on are announced.+- Previews and photos are never logged; names neither (v0 §11).