From 4eb7ad79d18c1d89784d2756a8652a1c0ce2d347 Mon Sep 17 00:00:00 2001
From: strawberry <strawberry@puppygock.gay>
Date: Tue, 1 Oct 2024 01:59:24 -0400
Subject: [PATCH] update last_seen_ip and last_seen_ts on updating device
 metadata

Signed-off-by: strawberry <strawberry@puppygock.gay>
---
 src/api/client/device.rs | 20 +++++++++++++++-----
 src/service/users/mod.rs | 11 -----------
 2 files changed, 15 insertions(+), 16 deletions(-)

diff --git a/src/api/client/device.rs b/src/api/client/device.rs
index 93eaa393..7e56f27e 100644
--- a/src/api/client/device.rs
+++ b/src/api/client/device.rs
@@ -1,10 +1,14 @@
 use axum::extract::State;
+use axum_client_ip::InsecureClientIp;
 use conduit::{err, Err};
 use futures::StreamExt;
-use ruma::api::client::{
-	device::{self, delete_device, delete_devices, get_device, get_devices, update_device},
-	error::ErrorKind,
-	uiaa::{AuthFlow, AuthType, UiaaInfo},
+use ruma::{
+	api::client::{
+		device::{self, delete_device, delete_devices, get_device, get_devices, update_device},
+		error::ErrorKind,
+		uiaa::{AuthFlow, AuthType, UiaaInfo},
+	},
+	MilliSecondsSinceUnixEpoch,
 };
 
 use super::SESSION_ID_LENGTH;
@@ -51,8 +55,10 @@ pub(crate) async fn get_device_route(
 /// # `PUT /_matrix/client/r0/devices/{deviceId}`
 ///
 /// Updates the metadata on a given device of the sender user.
+#[tracing::instrument(skip_all, fields(%client), name = "update_device")]
 pub(crate) async fn update_device_route(
-	State(services): State<crate::State>, body: Ruma<update_device::v3::Request>,
+	State(services): State<crate::State>, InsecureClientIp(client): InsecureClientIp,
+	body: Ruma<update_device::v3::Request>,
 ) -> Result<update_device::v3::Response> {
 	let sender_user = body.sender_user.as_ref().expect("user is authenticated");
 
@@ -63,6 +69,10 @@ pub(crate) async fn update_device_route(
 		.map_err(|_| err!(Request(NotFound("Device not found."))))?;
 
 	device.display_name.clone_from(&body.display_name);
+	device.last_seen_ip.clone_from(&Some(client.to_string()));
+	device
+		.last_seen_ts
+		.clone_from(&Some(MilliSecondsSinceUnixEpoch::now()));
 
 	services
 		.users
diff --git a/src/service/users/mod.rs b/src/service/users/mod.rs
index 1c079085..44d169dd 100644
--- a/src/service/users/mod.rs
+++ b/src/service/users/mod.rs
@@ -791,17 +791,6 @@ impl Service {
 	}
 
 	pub async fn update_device_metadata(&self, user_id: &UserId, device_id: &DeviceId, device: &Device) -> Result<()> {
-		// Only existing devices should be able to call this, but we shouldn't assert
-		// either...
-		let key = (user_id, device_id);
-		if self.db.userdeviceid_metadata.qry(&key).await.is_err() {
-			return Err!(Database(error!(
-				?user_id,
-				?device_id,
-				"Called update_device_metadata for a non-existent user and/or device"
-			)));
-		}
-
 		increment(&self.db.userid_devicelistversion, user_id.as_bytes());
 
 		let mut userdeviceid = user_id.as_bytes().to_vec();