Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

feat(sync): add sync client and manager (Phase 2)

Louis Beaumontfe6da1377320
diff --git a/screenpipe-core/src/sync/client.rs b/screenpipe-core/src/sync/client.rs
new file mode 100644
index 000000000..63fdeb573
--- /dev/null
+++ b/screenpipe-core/src/sync/client.rs
@@ -0,0 +1,869 @@
+//! Sync API client for cloud sync operations.
+//!
+//! This module provides the HTTP client for communicating with the
+//! Screenpipe cloud sync API.
+
+use reqwest::{Client, StatusCode};
+use serde::{Deserialize, Serialize};
+
+use super::blob::{BlobMetadata, BlobType};
+use super::error::{SyncError, SyncResult};
+use super::keys::{ExistingUserKeyData, NewUserKeyData, SyncKeys};
+
+/// Default API base URL
+const DEFAULT_API_URL: &str = "https://screenpi.pe/api/sync";
+
+/// Configuration for the sync client.
+#[derive(Debug, Clone)]
+pub struct SyncClientConfig {
+ /// Base URL for the sync API
+ pub api_url: String,
+ /// Authentication token (Clerk JWT)
+ pub auth_token: String,
+ /// Device ID (unique identifier for this device)
+ pub device_id: String,
+ /// Device name (user-friendly name)
+ pub device_name: String,
+ /// Device OS
+ pub device_os: String,
+ /// App version
+ pub app_version: Option<String>,
+}
+
+impl SyncClientConfig {
+ /// Create a new config with default API URL.
+ pub fn new(
+ auth_token: String,
+ device_id: String,
+ device_name: String,
+ device_os: String,
+ ) -> Self {
+ Self {
+ api_url: DEFAULT_API_URL.to_string(),
+ auth_token,
+ device_id,
+ device_name,
+ device_os,
+ app_version: None,
+ }
+ }
+
+ /// Set the API URL.
+ pub fn with_api_url(mut self, url: String) -> Self {
+ self.api_url = url;
+ self
+ }
+
+ /// Set the app version.
+ pub fn with_app_version(mut self, version: String) -> Self {
+ self.app_version = Some(version);
+ self
+ }
+}
+
+/// Client for sync API operations.
+pub struct SyncClient {
+ config: SyncClientConfig,
+ http: Client,
+}
+
+impl SyncClient {
+ /// Create a new sync client.
+ pub fn new(config: SyncClientConfig) -> SyncResult<Self> {
+ let http = Client::builder()
+ .timeout(std::time::Duration::from_secs(30))
+ .build()
+ .map_err(|e| SyncError::Network(format!("failed to create HTTP client: {}", e)))?;
+
+ Ok(Self { config, http })
+ }
+
+ /// Get the device ID.
+ pub fn device_id(&self) -> &str {
+ &self.config.device_id
+ }
+
+ // =========================================================================
+ // Init / Key Management
+ // =========================================================================
+
+ /// Initialize sync for a new user.
+ ///
+ /// This generates new encryption keys and registers them with the server.
+ pub async fn init_new_user(&self, password: &str) -> SyncResult<SyncKeys> {
+ let (key_data, keys) = NewUserKeyData::generate(password)?;
+
+ let request = InitRequest {
+ device_id: self.config.device_id.clone(),
+ device_name: self.config.device_name.clone(),
+ device_os: self.config.device_os.clone(),
+ device_os_version: None,
+ app_version: self.config.app_version.clone(),
+ encrypted_master_key: Some(key_data.encrypted_master_key),
+ master_key_nonce: Some(key_data.master_key_nonce),
+ salt: Some(key_data.salt),
+ };
+
+ let response: InitResponse = self.post("/init", &request).await?;
+
+ if !response.success {
+ return Err(SyncError::Server(
+ response.error.unwrap_or_else(|| "init failed".to_string()),
+ ));
+ }
+
+ Ok(keys)
+ }
+
+ /// Initialize sync for an existing user.
+ ///
+ /// This fetches the encrypted master key and derives the sync keys.
+ pub async fn init_existing_user(&self, password: &str) -> SyncResult<SyncKeys> {
+ let request = InitRequest {
+ device_id: self.config.device_id.clone(),
+ device_name: self.config.device_name.clone(),
+ device_os: self.config.device_os.clone(),
+ device_os_version: None,
+ app_version: self.config.app_version.clone(),
+ encrypted_master_key: None,
+ master_key_nonce: None,
+ salt: None,
+ };
+
+ let response: InitResponse = self.post("/init", &request).await?;
+
+ if !response.success {
+ return Err(SyncError::Server(
+ response.error.unwrap_or_else(|| "init failed".to_string()),
+ ));
+ }
+
+ // For existing users, server returns the key data
+ let key_data = ExistingUserKeyData {
+ salt: response.salt.ok_or_else(|| SyncError::Key("missing salt".to_string()))?,
+ encrypted_master_key: response
+ .encrypted_master_key
+ .ok_or_else(|| SyncError::Key("missing encrypted_master_key".to_string()))?,
+ master_key_nonce: response
+ .master_key_nonce
+ .ok_or_else(|| SyncError::Key("missing master_key_nonce".to_string()))?,
+ kdf_algorithm: response.kdf_algorithm.unwrap_or_else(|| "argon2id".to_string()),
+ kdf_iterations: response.kdf_iterations.unwrap_or(3),
+ kdf_memory: response.kdf_memory.unwrap_or(65536),
+ key_version: response.key_version.unwrap_or(1),
+ };
+
+ key_data.derive_keys(password)
+ }
+
+ /// Initialize sync - automatically detects new vs existing user.
+ pub async fn init(&self, password: &str) -> SyncResult<(SyncKeys, bool)> {
+ // Try as existing user first
+ let request = InitRequest {
+ device_id: self.config.device_id.clone(),
+ device_name: self.config.device_name.clone(),
+ device_os: self.config.device_os.clone(),
+ device_os_version: None,
+ app_version: self.config.app_version.clone(),
+ encrypted_master_key: None,
+ master_key_nonce: None,
+ salt: None,
+ };
+
+ let response: InitResponse = self.post("/init", &request).await?;
+
+ if !response.success {
+ let code = response.code.as_deref();
+ if code == Some("NO_SUBSCRIPTION") {
+ return Err(SyncError::NoSubscription);
+ }
+ return Err(SyncError::Server(
+ response.error.unwrap_or_else(|| "init failed".to_string()),
+ ));
+ }
+
+ let is_new_user = response.is_new_user.unwrap_or(false);
+
+ if is_new_user {
+ // New user - generate and upload keys
+ let keys = self.init_new_user(password).await?;
+ Ok((keys, true))
+ } else {
+ // Existing user - derive keys from server response
+ let key_data = ExistingUserKeyData {
+ salt: response.salt.ok_or_else(|| SyncError::Key("missing salt".to_string()))?,
+ encrypted_master_key: response
+ .encrypted_master_key
+ .ok_or_else(|| SyncError::Key("missing encrypted_master_key".to_string()))?,
+ master_key_nonce: response
+ .master_key_nonce
+ .ok_or_else(|| SyncError::Key("missing master_key_nonce".to_string()))?,
+ kdf_algorithm: response.kdf_algorithm.unwrap_or_else(|| "argon2id".to_string()),
+ kdf_iterations: response.kdf_iterations.unwrap_or(3),
+ kdf_memory: response.kdf_memory.unwrap_or(65536),
+ key_version: response.key_version.unwrap_or(1),
+ };
+
+ let keys = key_data.derive_keys(password)?;
+ Ok((keys, false))
+ }
+ }
+
+ // =========================================================================
+ // Upload
+ // =========================================================================
+
+ /// Request a presigned URL for uploading a blob.
+ pub async fn request_upload(
+ &self,
+ metadata: &BlobMetadata,
+ ) -> SyncResult<UploadUrlResponse> {
+ let request = UploadRequest {
+ blob_type: metadata.blob_type,
+ time_start: metadata.time_start.clone(),
+ time_end: metadata.time_end.clone(),
+ size_bytes: metadata.size_bytes,
+ checksum: metadata.checksum.clone(),
+ device_id: self.config.device_id.clone(),
+ key_version: metadata.key_version,
+ encryption_nonce: metadata.encryption_nonce.clone(),
+ search_tokens: if metadata.search_tokens.is_empty() {
+ None
+ } else {
+ Some(metadata.search_tokens.clone())
+ },
+ };
+
+ let response: UploadResponse = self.post("/upload", &request).await?;
+
+ if !response.success {
+ let code = response.code.as_deref();
+ if code == Some("QUOTA_EXCEEDED") {
+ return Err(SyncError::QuotaExceeded(
+ response.error.unwrap_or_else(|| "quota exceeded".to_string()),
+ ));
+ }
+ return Err(SyncError::Server(
+ response.error.unwrap_or_else(|| "upload request failed".to_string()),
+ ));
+ }
+
+ Ok(UploadUrlResponse {
+ blob_id: response.blob_id.ok_or_else(|| SyncError::Server("missing blob_id".to_string()))?,
+ upload_url: response.upload_url.ok_or_else(|| SyncError::Server("missing upload_url".to_string()))?,
+ expires_in: response.expires_in.unwrap_or(300),
+ })
+ }
+
+ /// Upload encrypted data to S3 using a presigned URL.
+ pub async fn upload_to_s3(&self, upload_url: &str, data: &[u8]) -> SyncResult<()> {
+ let response = self
+ .http
+ .put(upload_url)
+ .header("Content-Type", "application/octet-stream")
+ .body(data.to_vec())
+ .send()
+ .await?;
+
+ if !response.status().is_success() {
+ return Err(SyncError::Server(format!(
+ "S3 upload failed with status: {}",
+ response.status()
+ )));
+ }
+
+ Ok(())
+ }
+
+ /// Mark an upload as completed.
+ pub async fn complete_upload(&self, blob_id: &str) -> SyncResult<UploadCompleteResponse> {
+ let request = UploadCompleteRequest {
+ blob_id: blob_id.to_string(),
+ };
+
+ let response: UploadCompleteApiResponse = self.post("/upload/complete", &request).await?;
+
+ if !response.success {
+ return Err(SyncError::Server(
+ response.error.unwrap_or_else(|| "complete upload failed".to_string()),
+ ));
+ }
+
+ Ok(UploadCompleteResponse {
+ storage_used: response.storage_used.unwrap_or(0),
+ storage_limit: response.storage_limit.unwrap_or(0),
+ })
+ }
+
+ // =========================================================================
+ // Download
+ // =========================================================================
+
+ /// Get presigned download URLs for blobs.
+ pub async fn get_download_urls(&self, request: DownloadRequest) -> SyncResult<Vec<DownloadBlob>> {
+ let response: DownloadResponse = self.post("/download", &request).await?;
+
+ if !response.success {
+ return Err(SyncError::Server(
+ response.error.unwrap_or_else(|| "download request failed".to_string()),
+ ));
+ }
+
+ Ok(response.blobs)
+ }
+
+ /// Download encrypted data from S3.
+ pub async fn download_from_s3(&self, download_url: &str) -> SyncResult<Vec<u8>> {
+ let response = self.http.get(download_url).send().await?;
+
+ if !response.status().is_success() {
+ return Err(SyncError::Server(format!(
+ "S3 download failed with status: {}",
+ response.status()
+ )));
+ }
+
+ let bytes = response.bytes().await?;
+ Ok(bytes.to_vec())
+ }
+
+ // =========================================================================
+ // Search
+ // =========================================================================
+
+ /// Search for blobs by tokens.
+ pub async fn search(&self, request: SearchRequest) -> SyncResult<SearchResponse> {
+ let response: SearchApiResponse = self.post("/search", &request).await?;
+
+ if !response.success {
+ return Err(SyncError::Server(
+ response.error.unwrap_or_else(|| "search failed".to_string()),
+ ));
+ }
+
+ Ok(SearchResponse {
+ matches: response.matches,
+ total_matches: response.total_matches.unwrap_or(0),
+ })
+ }
+
+ // =========================================================================
+ // Status
+ // =========================================================================
+
+ /// Get sync status and quota information.
+ pub async fn get_status(&self) -> SyncResult<SyncStatus> {
+ let response: StatusResponse = self.get("/status").await?;
+
+ if !response.success {
+ return Err(SyncError::Server(
+ response.error.unwrap_or_else(|| "status request failed".to_string()),
+ ));
+ }
+
+ Ok(SyncStatus {
+ quota: response.quota.ok_or_else(|| SyncError::Server("missing quota".to_string()))?,
+ stats: response.stats.ok_or_else(|| SyncError::Server("missing stats".to_string()))?,
+ storage_breakdown: response.storage_breakdown,
+ })
+ }
+
+ // =========================================================================
+ // Devices
+ // =========================================================================
+
+ /// List registered devices.
+ pub async fn list_devices(&self) -> SyncResult<Vec<SyncDevice>> {
+ let response: DevicesResponse = self.get("/devices").await?;
+
+ if !response.success {
+ return Err(SyncError::Server(
+ response.error.unwrap_or_else(|| "list devices failed".to_string()),
+ ));
+ }
+
+ Ok(response.devices)
+ }
+
+ /// Remove a device.
+ pub async fn remove_device(&self, device_id: &str) -> SyncResult<()> {
+ let url = format!("{}/devices?device_id={}", self.config.api_url, device_id);
+
+ let response = self
+ .http
+ .delete(&url)
+ .header("Authorization", format!("Bearer {}", self.config.auth_token))
+ .send()
+ .await?;
+
+ if !response.status().is_success() {
+ let error_body: ApiError = response.json().await.unwrap_or(ApiError {
+ success: false,
+ error: Some("unknown error".to_string()),
+ code: None,
+ });
+ return Err(SyncError::Server(
+ error_body.error.unwrap_or_else(|| "remove device failed".to_string()),
+ ));
+ }
+
+ Ok(())
+ }
+
+ // =========================================================================
+ // HTTP Helpers
+ // =========================================================================
+
+ async fn post<T: Serialize, R: for<'de> Deserialize<'de>>(
+ &self,
+ path: &str,
+ body: &T,
+ ) -> SyncResult<R> {
+ let url = format!("{}{}", self.config.api_url, path);
+
+ let response = self
+ .http
+ .post(&url)
+ .header("Authorization", format!("Bearer {}", self.config.auth_token))
+ .header("X-Device-Id", &self.config.device_id)
+ .json(body)
+ .send()
+ .await?;
+
+ self.handle_response(response).await
+ }
+
+ async fn get<R: for<'de> Deserialize<'de>>(&self, path: &str) -> SyncResult<R> {
+ let url = format!("{}{}", self.config.api_url, path);
+
+ let response = self
+ .http
+ .get(&url)
+ .header("Authorization", format!("Bearer {}", self.config.auth_token))
+ .header("X-Device-Id", &self.config.device_id)
+ .send()
+ .await?;
+
+ self.handle_response(response).await
+ }
+
+ async fn handle_response<R: for<'de> Deserialize<'de>>(
+ &self,
+ response: reqwest::Response,
+ ) -> SyncResult<R> {
+ let status = response.status();
+
+ if status == StatusCode::UNAUTHORIZED {
+ return Err(SyncError::Auth("unauthorized".to_string()));
+ }
+
+ if status == StatusCode::FORBIDDEN {
+ // Could be quota or subscription issue
+ let error_body: ApiError = response.json().await.unwrap_or(ApiError {
+ success: false,
+ error: Some("forbidden".to_string()),
+ code: None,
+ });
+
+ if error_body.code.as_deref() == Some("NO_SUBSCRIPTION") {
+ return Err(SyncError::NoSubscription);
+ }
+ if error_body.code.as_deref() == Some("QUOTA_EXCEEDED") {
+ return Err(SyncError::QuotaExceeded(
+ error_body.error.unwrap_or_else(|| "quota exceeded".to_string()),
+ ));
+ }
+ if error_body.code.as_deref() == Some("DEVICE_LIMIT_EXCEEDED") {
+ return Err(SyncError::DeviceLimitExceeded);
+ }
+
+ return Err(SyncError::Server(
+ error_body.error.unwrap_or_else(|| "forbidden".to_string()),
+ ));
+ }
+
+ let body = response.text().await?;
+
+ serde_json::from_str(&body).map_err(|e| {
+ SyncError::Serialization(format!("failed to parse response: {} - body: {}", e, body))
+ })
+ }
+}
+
+// =============================================================================
+// API Types
+// =============================================================================
+
+#[derive(Debug, Serialize)]
+struct InitRequest {
+ device_id: String,
+ device_name: String,
+ device_os: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ device_os_version: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ app_version: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ encrypted_master_key: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ master_key_nonce: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ salt: Option<String>,
+}
+
+#[derive(Debug, Deserialize)]
+struct InitResponse {
+ success: bool,
+ #[serde(default)]
+ error: Option<String>,
+ #[serde(default)]
+ code: Option<String>,
+ #[serde(default)]
+ is_new_user: Option<bool>,
+ #[serde(default)]
+ salt: Option<String>,
+ #[serde(default)]
+ encrypted_master_key: Option<String>,
+ #[serde(default)]
+ master_key_nonce: Option<String>,
+ #[serde(default)]
+ kdf_algorithm: Option<String>,
+ #[serde(default)]
+ kdf_iterations: Option<u32>,
+ #[serde(default)]
+ kdf_memory: Option<u32>,
+ #[serde(default)]
+ key_version: Option<u32>,
+}
+
+#[derive(Debug, Serialize)]
+struct UploadRequest {
+ blob_type: BlobType,
+ time_start: String,
+ time_end: String,
+ size_bytes: u64,
+ checksum: String,
+ device_id: String,
+ key_version: u32,
+ encryption_nonce: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ search_tokens: Option<Vec<String>>,
+}
+
+#[derive(Debug, Deserialize)]
+struct UploadResponse {
+ success: bool,
+ #[serde(default)]
+ error: Option<String>,
+ #[serde(default)]
+ code: Option<String>,
+ #[serde(default)]
+ blob_id: Option<String>,
+ #[serde(default)]
+ upload_url: Option<String>,
+ #[serde(default)]
+ expires_in: Option<u32>,
+}
+
+/// Response from upload URL request.
+#[derive(Debug)]
+pub struct UploadUrlResponse {
+ /// The blob ID assigned by the server
+ pub blob_id: String,
+ /// Presigned S3 upload URL
+ pub upload_url: String,
+ /// Seconds until URL expires
+ pub expires_in: u32,
+}
+
+#[derive(Debug, Serialize)]
+struct UploadCompleteRequest {
+ blob_id: String,
+}
+
+#[derive(Debug, Deserialize)]
+struct UploadCompleteApiResponse {
+ success: bool,
+ #[serde(default)]
+ error: Option<String>,
+ #[serde(default)]
+ storage_used: Option<u64>,
+ #[serde(default)]
+ storage_limit: Option<u64>,
+}
+
+/// Response from completing an upload.
+#[derive(Debug)]
+pub struct UploadCompleteResponse {
+ /// Current storage used in bytes
+ pub storage_used: u64,
+ /// Storage limit in bytes
+ pub storage_limit: u64,
+}
+
+/// Request for downloading blobs.
+#[derive(Debug, Clone, Serialize)]
+pub struct DownloadRequest {
+ /// Specific blob IDs to download
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub blob_ids: Option<Vec<String>>,
+ /// Time range filter
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub time_range: Option<TimeRange>,
+ /// Blob types to include
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub blob_types: Option<Vec<BlobType>>,
+ /// Maximum number of blobs to return
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub limit: Option<u32>,
+}
+
+/// Time range for filtering.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct TimeRange {
+ /// Start of time range (ISO 8601)
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub start: Option<String>,
+ /// End of time range (ISO 8601)
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub end: Option<String>,
+}
+
+#[derive(Debug, Deserialize)]
+struct DownloadResponse {
+ success: bool,
+ #[serde(default)]
+ error: Option<String>,
+ #[serde(default)]
+ blobs: Vec<DownloadBlob>,
+}
+
+/// Information about a blob available for download.
+#[derive(Debug, Clone, Deserialize)]
+pub struct DownloadBlob {
+ /// Blob ID
+ pub blob_id: String,
+ /// Blob type
+ pub blob_type: BlobType,
+ /// Presigned download URL
+ pub download_url: String,
+ /// Encryption nonce (base64)
+ pub encryption_nonce: String,
+ /// Key version used for encryption
+ pub key_version: u32,
+ /// Size in bytes
+ pub size_bytes: u64,
+ /// Checksum for verification
+ pub checksum: String,
+ /// Start of time range
+ pub time_start: String,
+ /// End of time range
+ pub time_end: String,
+}
+
+/// Request for searching blobs.
+#[derive(Debug, Clone, Serialize)]
+pub struct SearchRequest {
+ /// Search tokens (base64 encoded HMAC tokens)
+ pub search_tokens: Vec<String>,
+ /// Optional time range filter
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub time_range: Option<TimeRange>,
+ /// Optional blob type filter
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub blob_types: Option<Vec<BlobType>>,
+ /// Maximum results
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub limit: Option<u32>,
+}
+
+#[derive(Debug, Deserialize)]
+struct SearchApiResponse {
+ success: bool,
+ #[serde(default)]
+ error: Option<String>,
+ #[serde(default)]
+ matches: Vec<SearchMatch>,
+ #[serde(default)]
+ total_matches: Option<u32>,
+}
+
+/// Search response.
+#[derive(Debug)]
+pub struct SearchResponse {
+ /// Matching blobs
+ pub matches: Vec<SearchMatch>,
+ /// Total number of matches
+ pub total_matches: u32,
+}
+
+/// A search result match.
+#[derive(Debug, Clone, Deserialize)]
+pub struct SearchMatch {
+ /// Blob ID
+ pub blob_id: String,
+ /// Blob type
+ pub blob_type: BlobType,
+ /// Start of time range
+ pub time_start: String,
+ /// End of time range
+ pub time_end: String,
+ /// Number of matching tokens
+ pub match_count: u32,
+}
+
+#[derive(Debug, Deserialize)]
+struct StatusResponse {
+ success: bool,
+ #[serde(default)]
+ error: Option<String>,
+ #[serde(default)]
+ quota: Option<SyncQuota>,
+ #[serde(default)]
+ stats: Option<SyncStats>,
+ #[serde(default)]
+ storage_breakdown: Option<StorageBreakdown>,
+}
+
+/// Sync status response.
+#[derive(Debug)]
+pub struct SyncStatus {
+ /// Quota information
+ pub quota: SyncQuota,
+ /// Sync statistics
+ pub stats: SyncStats,
+ /// Storage breakdown by type
+ pub storage_breakdown: Option<StorageBreakdown>,
+}
+
+/// Quota information.
+#[derive(Debug, Clone, Deserialize)]
+pub struct SyncQuota {
+ /// Storage used in bytes
+ pub storage_used: u64,
+ /// Storage limit in bytes
+ pub storage_limit: u64,
+ /// Number of registered devices
+ pub device_count: u32,
+ /// Maximum allowed devices
+ pub device_limit: u32,
+ /// Whether sync is allowed
+ pub can_sync: bool,
+ /// Current sync tier
+ pub sync_tier: Option<String>,
+}
+
+/// Sync statistics.
+#[derive(Debug, Clone, Deserialize)]
+pub struct SyncStats {
+ /// Total number of blobs
+ pub total_blobs: u32,
+ /// Total bytes stored
+ pub total_bytes: u64,
+ /// Last sync timestamp
+ pub last_sync_at: Option<String>,
+ /// Oldest data timestamp
+ pub oldest_data: Option<String>,
+ /// Newest data timestamp
+ pub newest_data: Option<String>,
+}
+
+/// Storage breakdown by blob type.
+#[derive(Debug, Clone, Deserialize)]
+pub struct StorageBreakdown {
+ /// Bytes used by frames
+ pub frames_bytes: u64,
+ /// Bytes used by audio
+ pub audio_bytes: u64,
+ /// Bytes used by transcripts
+ pub transcripts_bytes: u64,
+ /// Bytes used by OCR
+ pub ocr_bytes: u64,
+}
+
+#[derive(Debug, Deserialize)]
+struct DevicesResponse {
+ success: bool,
+ #[serde(default)]
+ error: Option<String>,
+ #[serde(default)]
+ devices: Vec<SyncDevice>,
+}
+
+/// A registered sync device.
+#[derive(Debug, Clone, Deserialize)]
+pub struct SyncDevice {
+ /// Database ID
+ pub id: String,
+ /// Device ID
+ pub device_id: String,
+ /// User-friendly name
+ pub device_name: Option<String>,
+ /// Operating system
+ pub device_os: String,
+ /// Last sync timestamp
+ pub last_sync_at: Option<String>,
+ /// Created timestamp
+ pub created_at: String,
+}
+
+#[derive(Debug, Deserialize)]
+struct ApiError {
+ #[allow(dead_code)]
+ success: bool,
+ #[serde(default)]
+ error: Option<String>,
+ #[serde(default)]
+ code: Option<String>,
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_config_builder() {
+ let config = SyncClientConfig::new(
+ "token".to_string(),
+ "device-123".to_string(),
+ "My MacBook".to_string(),
+ "macos".to_string(),
+ )
+ .with_api_url("https://custom.api.com".to_string())
+ .with_app_version("1.0.0".to_string());
+
+ assert_eq!(config.api_url, "https://custom.api.com");
+ assert_eq!(config.app_version, Some("1.0.0".to_string()));
+ }
+
+ #[test]
+ fn test_download_request_serialization() {
+ let request = DownloadRequest {
+ blob_ids: Some(vec!["blob-1".to_string()]),
+ time_range: Some(TimeRange {
+ start: Some("2024-01-01T00:00:00Z".to_string()),
+ end: None,
+ }),
+ blob_types: Some(vec![BlobType::Ocr, BlobType::Transcripts]),
+ limit: Some(100),
+ };
+
+ let json = serde_json::to_string(&request).unwrap();
+ assert!(json.contains("blob-1"));
+ assert!(json.contains("ocr"));
+ }
+
+ #[test]
+ fn test_search_request_serialization() {
+ let request = SearchRequest {
+ search_tokens: vec!["dG9rZW4x".to_string(), "dG9rZW4y".to_string()],
+ time_range: None,
+ blob_types: None,
+ limit: Some(50),
+ };
+
+ let json = serde_json::to_string(&request).unwrap();
+ assert!(json.contains("search_tokens"));
+ assert!(json.contains("dG9rZW4x"));
+ }
+}
diff --git a/screenpipe-core/src/sync/manager.rs b/screenpipe-core/src/sync/manager.rs
new file mode 100644
index 000000000..69917b04b
--- /dev/null
+++ b/screenpipe-core/src/sync/manager.rs
@@ -0,0 +1,339 @@
+//! High-level sync manager for coordinating sync operations.
+//!
+//! This module provides a simple interface for common sync operations,
+//! handling the encryption/decryption and API communication internally.
+
+use std::sync::Arc;
+use tokio::sync::RwLock;
+
+use super::blob::{decrypt_blob, encrypt_blob, BlobMetadata, BlobType, DecryptedBlob};
+use super::client::{
+ DownloadBlob, DownloadRequest, SearchRequest, SyncClient, SyncClientConfig, SyncStatus,
+ TimeRange,
+};
+use super::crypto::generate_search_token;
+use super::error::{SyncError, SyncResult};
+use super::keys::SyncKeys;
+
+/// High-level manager for sync operations.
+///
+/// This struct holds the sync client and encryption keys, providing
+/// a simple interface for uploading, downloading, and searching data.
+pub struct SyncManager {
+ client: SyncClient,
+ keys: Arc<RwLock<Option<SyncKeys>>>,
+}
+
+impl SyncManager {
+ /// Create a new sync manager.
+ pub fn new(config: SyncClientConfig) -> SyncResult<Self> {
+ let client = SyncClient::new(config)?;
+ Ok(Self {
+ client,
+ keys: Arc::new(RwLock::new(None)),
+ })
+ }
+
+ /// Check if the manager is initialized (has keys).
+ pub async fn is_initialized(&self) -> bool {
+ self.keys.read().await.is_some()
+ }
+
+ /// Initialize sync with the user's password.
+ ///
+ /// This will either create new encryption keys (for new users) or
+ /// derive keys from the server's stored encrypted master key.
+ ///
+ /// Returns true if this is a new user, false if existing.
+ pub async fn initialize(&self, password: &str) -> SyncResult<bool> {
+ let (keys, is_new) = self.client.init(password).await?;
+ *self.keys.write().await = Some(keys);
+ Ok(is_new)
+ }
+
+ /// Lock the manager (clear keys from memory).
+ ///
+ /// Call this when the user logs out or the app is locked.
+ pub async fn lock(&self) {
+ *self.keys.write().await = None;
+ }
+
+ /// Get a reference to the keys, or error if not initialized.
+ async fn require_keys(&self) -> SyncResult<tokio::sync::RwLockReadGuard<'_, Option<SyncKeys>>> {
+ let guard = self.keys.read().await;
+ if guard.is_none() {
+ return Err(SyncError::Key("sync not initialized".to_string()));
+ }
+ Ok(guard)
+ }
+
+ // =========================================================================
+ // Upload Operations
+ // =========================================================================
+
+ /// Upload data to the cloud.
+ ///
+ /// This encrypts the data locally and uploads it to S3.
+ ///
+ /// # Arguments
+ /// * `data` - The plaintext data to upload
+ /// * `blob_type` - The type of data
+ /// * `time_start` - Start of time range (ISO 8601)
+ /// * `time_end` - End of time range (ISO 8601)
+ /// * `text_content` - Optional text for search indexing
+ ///
+ /// # Returns
+ /// The blob ID and updated storage usage
+ pub async fn upload(
+ &self,
+ data: &[u8],
+ blob_type: BlobType,
+ time_start: &str,
+ time_end: &str,
+ text_content: Option<&str>,
+ ) -> SyncResult<UploadResult> {
+ let keys_guard = self.require_keys().await?;
+ let keys = keys_guard.as_ref().unwrap();
+
+ // Encrypt the data
+ let encrypted = encrypt_blob(data, blob_type, keys, text_content)?;
+
+ // Create metadata
+ let metadata = BlobMetadata::from_encrypted_blob(
+ &encrypted,
+ time_start,
+ time_end,
+ keys.key_version(),
+ );
+
+ // Request upload URL
+ let upload_info = self.client.request_upload(&metadata).await?;
+
+ // Upload to S3
+ self.client
+ .upload_to_s3(&upload_info.upload_url, &encrypted.ciphertext)
+ .await?;
+
+ // Mark upload complete
+ let complete = self.client.complete_upload(&upload_info.blob_id).await?;
+
+ Ok(UploadResult {
+ blob_id: upload_info.blob_id,
+ storage_used: complete.storage_used,
+ storage_limit: complete.storage_limit,
+ })
+ }
+
+ // =========================================================================
+ // Download Operations
+ // =========================================================================
+
+ /// Download and decrypt blobs by ID.
+ pub async fn download_by_ids(&self, blob_ids: Vec<String>) -> SyncResult<Vec<DecryptedBlob>> {
+ let keys_guard = self.require_keys().await?;
+ let keys = keys_guard.as_ref().unwrap();
+
+ let request = DownloadRequest {
+ blob_ids: Some(blob_ids),
+ time_range: None,
+ blob_types: None,
+ limit: None,
+ };
+
+ let blobs = self.client.get_download_urls(request).await?;
+ self.download_and_decrypt_blobs(&blobs, keys).await
+ }
+
+ /// Download and decrypt blobs by time range.
+ pub async fn download_by_time_range(
+ &self,
+ start: Option<String>,
+ end: Option<String>,
+ blob_types: Option<Vec<BlobType>>,
+ limit: Option<u32>,
+ ) -> SyncResult<Vec<DecryptedBlob>> {
+ let keys_guard = self.require_keys().await?;
+ let keys = keys_guard.as_ref().unwrap();
+
+ let request = DownloadRequest {
+ blob_ids: None,
+ time_range: Some(TimeRange { start, end }),
+ blob_types,
+ limit,
+ };
+
+ let blobs = self.client.get_download_urls(request).await?;
+ self.download_and_decrypt_blobs(&blobs, keys).await
+ }
+
+ async fn download_and_decrypt_blobs(
+ &self,
+ blobs: &[DownloadBlob],
+ keys: &SyncKeys,
+ ) -> SyncResult<Vec<DecryptedBlob>> {
+ let mut results = Vec::with_capacity(blobs.len());
+
+ for blob in blobs {
+ // Download from S3
+ let ciphertext = self.client.download_from_s3(&blob.download_url).await?;
+
+ // Decrypt
+ let decrypted = decrypt_blob(
+ &ciphertext,
+ &blob.encryption_nonce,
+ Some(&blob.checksum),
+ blob.blob_type,
+ keys,
+ )?;
+
+ results.push(decrypted);
+ }
+
+ Ok(results)
+ }
+
+ // =========================================================================
+ // Search Operations
+ // =========================================================================
+
+ /// Search for blobs containing the given keywords.
+ ///
+ /// This generates search tokens from the keywords and searches the
+ /// encrypted index on the server.
+ pub async fn search(
+ &self,
+ keywords: &[&str],
+ time_range: Option<TimeRange>,
+ blob_types: Option<Vec<BlobType>>,
+ limit: Option<u32>,
+ ) -> SyncResult<SearchResult> {
+ let keys_guard = self.require_keys().await?;
+ let keys = keys_guard.as_ref().unwrap();
+
+ // Generate search tokens
+ let mut tokens = Vec::with_capacity(keywords.len());
+ for keyword in keywords {
+ let token = generate_search_token(keyword, keys.search_key())?;
+ tokens.push(base64::engine::general_purpose::STANDARD.encode(token));
+ }
+
+ use base64::Engine;
+
+ let request = SearchRequest {
+ search_tokens: tokens,
+ time_range,
+ blob_types,
+ limit,
+ };
+
+ let response = self.client.search(request).await?;
+
+ Ok(SearchResult {
+ blob_ids: response.matches.iter().map(|m| m.blob_id.clone()).collect(),
+ matches: response.matches.into_iter().map(|m| SearchMatchInfo {
+ blob_id: m.blob_id,
+ blob_type: m.blob_type,
+ time_start: m.time_start,
+ time_end: m.time_end,
+ match_count: m.match_count,
+ }).collect(),
+ total: response.total_matches,
+ })
+ }
+
+ /// Search and download matching blobs.
+ ///
+ /// Convenience method that combines search + download.
+ pub async fn search_and_download(
+ &self,
+ keywords: &[&str],
+ time_range: Option<TimeRange>,
+ blob_types: Option<Vec<BlobType>>,
+ limit: Option<u32>,
+ ) -> SyncResult<Vec<DecryptedBlob>> {
+ let search_result = self.search(keywords, time_range, blob_types, limit).await?;
+
+ if search_result.blob_ids.is_empty() {
+ return Ok(Vec::new());
+ }
+
+ self.download_by_ids(search_result.blob_ids).await
+ }
+
+ // =========================================================================
+ // Status Operations
+ // =========================================================================
+
+ /// Get sync status and quota information.
+ pub async fn get_status(&self) -> SyncResult<SyncStatus> {
+ self.client.get_status().await
+ }
+
+ /// Get the client for advanced operations.
+ pub fn client(&self) -> &SyncClient {
+ &self.client
+ }
+}
+
+/// Result of an upload operation.
+#[derive(Debug)]
+pub struct UploadResult {
+ /// The blob ID assigned by the server
+ pub blob_id: String,
+ /// Current storage used in bytes
+ pub storage_used: u64,
+ /// Storage limit in bytes
+ pub storage_limit: u64,
+}
+
+/// Result of a search operation.
+#[derive(Debug)]
+pub struct SearchResult {
+ /// Matching blob IDs
+ pub blob_ids: Vec<String>,
+ /// Detailed match information
+ pub matches: Vec<SearchMatchInfo>,
+ /// Total number of matches
+ pub total: u32,
+}
+
+/// Information about a search match.
+#[derive(Debug)]
+pub struct SearchMatchInfo {
+ /// Blob ID
+ pub blob_id: String,
+ /// Blob type
+ pub blob_type: BlobType,
+ /// Start of time range
+ pub time_start: String,
+ /// End of time range
+ pub time_end: String,
+ /// Number of matching tokens
+ pub match_count: u32,
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_upload_result() {
+ let result = UploadResult {
+ blob_id: "blob-123".to_string(),
+ storage_used: 1024,
+ storage_limit: 1024 * 1024,
+ };
+ assert_eq!(result.blob_id, "blob-123");
+ }
+
+ #[test]
+ fn test_search_result() {
+ let result = SearchResult {
+ blob_ids: vec!["blob-1".to_string(), "blob-2".to_string()],
+ matches: vec![],
+ total: 2,
+ };
+ assert_eq!(result.blob_ids.len(), 2);
+ assert_eq!(result.total, 2);
+ }
+}
diff --git a/screenpipe-core/src/sync/mod.rs b/screenpipe-core/src/sync/mod.rs
index 3f2551cb1..0558c7ac3 100644
--- a/screenpipe-core/src/sync/mod.rs
+++ b/screenpipe-core/src/sync/mod.rs
@@ -86,15 +86,23 @@
//! ```
pub mod blob;
+pub mod client;
pub mod crypto;
pub mod error;
pub mod keys;
+pub mod manager;
// Re-exports for convenient access
pub use blob::{decrypt_blob, encrypt_blob, BlobMetadata, BlobType, DecryptedBlob, EncryptedBlob};
+pub use client::{
+ DownloadBlob, DownloadRequest, SearchMatch, SearchRequest, SearchResponse, StorageBreakdown,
+ SyncClient, SyncClientConfig, SyncDevice, SyncQuota, SyncStats, SyncStatus, TimeRange,
+ UploadCompleteResponse, UploadUrlResponse,
+};
pub use crypto::{
compute_checksum, generate_nonce, generate_salt, generate_search_token,
generate_search_tokens_from_text, HMAC_SIZE, KEY_SIZE, NONCE_SIZE, SALT_SIZE,
};
pub use error::{SyncError, SyncResult};
pub use keys::{ExistingUserKeyData, NewUserKeyData, SyncKeys};
+pub use manager::{SearchMatchInfo, SearchResult, SyncManager, UploadResult};