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

OpenAPI Codegen (#1103)

neo773dff09e9050b6
diff --git a/Cargo.toml b/Cargo.toml
index e340745ea..3d5007686 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -39,7 +39,7 @@ reqwest = { version = "0.11", features = ["blocking", "multipart", "json"] }
criterion = { version = "0.5.1", features = ["async_tokio"] }
vcpkg = "0.2"
cc = "1.0"
-
+oasgen = { version = "0.22.0", features = ["axum", "chrono"] }
once_cell = "1.20.2"
sentry = { version = "0.36.0", features = ["tracing"] }
diff --git a/screenpipe-audio/Cargo.toml b/screenpipe-audio/Cargo.toml
index 3c756f456..3b7ac7a71 100644
--- a/screenpipe-audio/Cargo.toml
+++ b/screenpipe-audio/Cargo.toml
@@ -16,6 +16,7 @@ which = "7.0.0"
[dependencies]
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
+oasgen = { workspace = true }
# Cross-platform audio capture
cpal = { git = "https://github.com/Kree0/cpal.git", branch = "master" }
diff --git a/screenpipe-audio/src/core.rs b/screenpipe-audio/src/core.rs
index 48ecae9ae..a035d4fd6 100644
--- a/screenpipe-audio/src/core.rs
+++ b/screenpipe-audio/src/core.rs
@@ -14,6 +14,8 @@ use std::sync::Arc;
use std::time::Duration;
use std::{fmt, thread};
use tokio::sync::{broadcast, oneshot};
+use oasgen::OaSchema;
+
lazy_static! {
pub static ref LAST_AUDIO_CAPTURE: AtomicU64 = AtomicU64::new(
std::time::SystemTime::now()
@@ -51,13 +53,13 @@ pub struct DeviceControl {
pub is_paused: bool,
}
-#[derive(Clone, Eq, PartialEq, Hash, Serialize, Debug, Deserialize)]
+#[derive(OaSchema, Clone, Eq, PartialEq, Hash, Serialize, Debug, Deserialize)]
pub enum DeviceType {
Input,
Output,
}
-#[derive(Clone, Eq, PartialEq, Hash, Serialize, Debug)]
+#[derive(OaSchema, Clone, Eq, PartialEq, Hash, Serialize, Debug)]
pub struct AudioDevice {
pub name: String,
pub device_type: DeviceType,
diff --git a/screenpipe-server/Cargo.toml b/screenpipe-server/Cargo.toml
index 2d2f22b60..2746868b0 100644
--- a/screenpipe-server/Cargo.toml
+++ b/screenpipe-server/Cargo.toml
@@ -12,6 +12,7 @@ edition = { workspace = true }
[dependencies]
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
+oasgen = { workspace = true }
screenpipe-events = { path = "../screenpipe-events" }
screenpipe-vision = { path = "../screenpipe-vision" }
diff --git a/screenpipe-server/src/bin/screenpipe-server.rs b/screenpipe-server/src/bin/screenpipe-server.rs
index a4a0685f3..c298267a6 100644
--- a/screenpipe-server/src/bin/screenpipe-server.rs
+++ b/screenpipe-server/src/bin/screenpipe-server.rs
@@ -18,7 +18,7 @@ use screenpipe_server::{
create_migration_worker, handle_index_command,
pipe_manager::PipeInfo,
start_continuous_recording, watch_pid, DatabaseManager, MigrationCommand, MigrationConfig,
- MigrationStatus, PipeManager, ResourceMonitor, Server,
+ MigrationStatus, PipeManager, ResourceMonitor, SCServer,
};
use screenpipe_vision::monitor::list_monitors;
#[cfg(target_os = "macos")]
@@ -796,7 +796,7 @@ async fn main() -> anyhow::Result<()> {
let (audio_devices_tx, _) = broadcast::channel(100);
// TODO: Add SSE stream for realtime audio transcription
- let server = Server::new(
+ let server = SCServer::new(
db_server,
SocketAddr::from(([127, 0, 0, 1], cli.port)),
local_data_dir_clone_2,
diff --git a/screenpipe-server/src/db_types.rs b/screenpipe-server/src/db_types.rs
index ef0060c9f..6af279d3b 100644
--- a/screenpipe-server/src/db_types.rs
+++ b/screenpipe-server/src/db_types.rs
@@ -1,11 +1,12 @@
use chrono::{DateTime, Utc};
+use oasgen::OaSchema;
use screenpipe_audio::DeviceType;
use serde::{Deserialize, Serialize};
use sqlx::FromRow;
use std::error::Error as StdError;
use std::fmt::{self, Display};
-#[derive(Debug)]
+#[derive(OaSchema, Debug)]
pub struct DatabaseError(pub String);
impl fmt::Display for DatabaseError {
@@ -16,7 +17,7 @@ impl fmt::Display for DatabaseError {
impl StdError for DatabaseError {}
-#[derive(Debug, Serialize, Deserialize)]
+#[derive(OaSchema, Debug, Serialize, Deserialize)]
pub enum SearchResult {
OCR(OCRResult),
Audio(AudioResult),
@@ -48,7 +49,7 @@ pub struct OCRResultRaw {
pub focused: Option<bool>,
}
-#[derive(Debug, Serialize, Deserialize)]
+#[derive(OaSchema, Debug, Serialize, Deserialize)]
pub struct OCRResult {
pub frame_id: i64,
pub frame_name: String,
@@ -65,7 +66,7 @@ pub struct OCRResult {
pub focused: Option<bool>,
}
-#[derive(Debug, Deserialize, PartialEq, Default, Clone)]
+#[derive(OaSchema, Debug, Deserialize, PartialEq, Default, Clone)]
#[serde(rename_all = "lowercase")]
pub enum ContentType {
#[default]
@@ -100,14 +101,14 @@ pub struct AudioResultRaw {
pub end_time: Option<f64>,
}
-#[derive(Debug, Serialize, Deserialize, FromRow, Clone)]
+#[derive(OaSchema, Debug, Serialize, Deserialize, FromRow, Clone)]
pub struct Speaker {
pub id: i64,
pub name: String,
pub metadata: String,
}
-#[derive(Debug, Serialize, Deserialize)]
+#[derive(OaSchema, Debug, Serialize, Deserialize)]
pub struct AudioResult {
pub audio_chunk_id: i64,
pub transcription: String,
@@ -123,14 +124,14 @@ pub struct AudioResult {
pub end_time: Option<f64>,
}
-#[derive(Debug, Deserialize, PartialEq)]
+#[derive(OaSchema, Debug, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum TagContentType {
Vision,
Audio,
}
-#[derive(Debug, Serialize, Deserialize, sqlx::FromRow)]
+#[derive(OaSchema, Debug, Serialize, Deserialize, sqlx::FromRow)]
pub struct UiContent {
pub id: i64,
#[sqlx(rename = "text_output")]
@@ -147,7 +148,7 @@ pub struct UiContent {
pub browser_url: Option<String>,
}
-#[derive(Debug, Clone)]
+#[derive(OaSchema, Debug, Clone)]
pub struct FrameData {
pub frame_id: i64,
pub timestamp: DateTime<Utc>,
@@ -156,7 +157,7 @@ pub struct FrameData {
pub audio_entries: Vec<AudioEntry>,
}
-#[derive(Debug, Clone)]
+#[derive(OaSchema, Debug, Clone)]
pub struct OCREntry {
pub text: String,
pub app_name: String,
@@ -165,7 +166,7 @@ pub struct OCREntry {
pub video_file_path: String,
}
-#[derive(Debug, Clone)]
+#[derive(OaSchema, Debug, Clone)]
pub struct AudioEntry {
pub transcription: String,
pub device_name: String,
@@ -174,14 +175,14 @@ pub struct AudioEntry {
pub duration_secs: f64,
}
-#[derive(Debug, Clone)]
+#[derive(OaSchema, Debug, Clone)]
pub struct TimeSeriesChunk {
pub frames: Vec<FrameData>,
pub start_time: DateTime<Utc>,
pub end_time: DateTime<Utc>,
}
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+#[derive(OaSchema, Debug, Clone, Copy, PartialEq, Eq)]
pub enum ContentSource {
Screen,
Audio,
@@ -196,14 +197,14 @@ impl Display for ContentSource {
}
}
-#[derive(Debug, FromRow)]
+#[derive(OaSchema, Debug, FromRow)]
pub struct AudioChunk {
pub id: i64,
pub file_path: String,
pub timestamp: DateTime<Utc>,
}
-#[derive(Debug, FromRow)]
+#[derive(OaSchema, Debug, FromRow)]
pub struct AudioChunksResponse {
pub audio_chunk_id: i64,
pub start_time: Option<f64>,
@@ -228,14 +229,14 @@ pub struct OcrTextBlock {
pub line_num: String,
}
-#[derive(Debug, Serialize, Clone)]
+#[derive(OaSchema, Debug, Serialize, Clone)]
pub struct TextPosition {
pub text: String,
pub confidence: f32,
pub bounds: TextBounds,
}
-#[derive(Debug, Serialize, Clone)]
+#[derive(OaSchema, Debug, Serialize, Clone)]
pub struct TextBounds {
pub left: f32,
pub top: f32,
@@ -243,7 +244,7 @@ pub struct TextBounds {
pub height: f32,
}
-#[derive(Serialize)]
+#[derive(OaSchema, Serialize)]
pub struct SearchMatch {
pub frame_id: i64,
pub timestamp: DateTime<Utc>,
@@ -267,7 +268,7 @@ pub struct FrameRow {
pub text_json: String,
}
-#[derive(Deserialize, PartialEq, Default)]
+#[derive(Deserialize, OaSchema, PartialEq, Default)]
pub enum Order {
#[serde(rename = "ascending")]
Ascending,
diff --git a/screenpipe-server/src/embedding/embedding_endpoint.rs b/screenpipe-server/src/embedding/embedding_endpoint.rs
index d21ad6184..e6e9c83c9 100644
--- a/screenpipe-server/src/embedding/embedding_endpoint.rs
+++ b/screenpipe-server/src/embedding/embedding_endpoint.rs
@@ -1,4 +1,5 @@
use axum::Json;
+use oasgen::{oasgen, OaSchema};
use once_cell::sync::OnceCell;
use screenpipe_core::model::EmbeddingModel;
use serde::{Deserialize, Serialize};
@@ -9,7 +10,7 @@ use tracing::info;
static EMBEDDING_MODEL: OnceCell<Arc<Mutex<EmbeddingModel>>> = OnceCell::new();
// OpenAI-like request/response types
-#[derive(Deserialize)]
+#[derive(OaSchema, Deserialize)]
#[allow(dead_code)]
pub struct EmbeddingRequest {
model: String,
@@ -20,7 +21,7 @@ pub struct EmbeddingRequest {
user: Option<String>,
}
-#[derive(Deserialize)]
+#[derive(OaSchema, Deserialize)]
#[serde(untagged)]
pub enum EmbeddingInput {
#[serde(rename = "single")]
@@ -29,7 +30,7 @@ pub enum EmbeddingInput {
Multiple(Vec<String>),
}
-#[derive(Serialize)]
+#[derive(OaSchema, Serialize)]
pub struct EmbeddingResponse {
object: String,
data: Vec<EmbeddingData>,
@@ -37,14 +38,14 @@ pub struct EmbeddingResponse {
usage: Usage,
}
-#[derive(Serialize)]
+#[derive(OaSchema, Serialize)]
pub struct EmbeddingData {
object: String,
embedding: Vec<f32>,
index: usize,
}
-#[derive(Serialize)]
+#[derive(OaSchema, Serialize)]
pub struct Usage {
prompt_tokens: usize,
total_tokens: usize,
@@ -71,6 +72,7 @@ pub async fn get_or_initialize_model() -> anyhow::Result<Arc<Mutex<EmbeddingMode
.map(|model| model.clone())
}
+#[oasgen]
pub async fn create_embeddings(
Json(request): Json<EmbeddingRequest>,
) -> Result<Json<EmbeddingResponse>, (axum::http::StatusCode, String)> {
diff --git a/screenpipe-server/src/lib.rs b/screenpipe-server/src/lib.rs
index d195b5439..7bf0d5428 100644
--- a/screenpipe-server/src/lib.rs
+++ b/screenpipe-server/src/lib.rs
@@ -30,12 +30,11 @@ pub use migration_worker::{
pub use pipe_manager::PipeManager;
pub use resource_monitor::{ResourceMonitor, RestartSignal};
pub use screenpipe_core::Language;
-pub use server::create_router;
pub use server::health_check;
pub use server::AppState;
pub use server::ContentItem;
pub use server::HealthCheckResponse;
pub use server::PaginatedResponse;
-pub use server::Server;
+pub use server::SCServer;
pub use server::{api_list_monitors, MonitorInfo};
pub use video::VideoCapture;
diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rs
index 13f9b6221..399f7302e 100644
--- a/screenpipe-server/src/server.rs
+++ b/screenpipe-server/src/server.rs
@@ -9,6 +9,8 @@ use axum::{
routing::{get, post},
serve, Router,
};
+use oasgen::{oasgen, OaSchema, Server};
+
use tokio_util::io::ReaderStream;
use tokio::fs::File;
@@ -86,7 +88,7 @@ pub struct AppState {
}
// Update the SearchQuery struct
-#[derive(Deserialize)]
+#[derive(OaSchema, Deserialize)]
pub(crate) struct SearchQuery {
q: Option<String>,
#[serde(flatten)]
@@ -120,7 +122,7 @@ pub(crate) struct SearchQuery {
browser_url: Option<String>,
}
-#[derive(Deserialize)]
+#[derive(OaSchema, Deserialize)]
pub(crate) struct PaginationQuery {
#[serde(default = "default_limit")]
#[serde(deserialize_with = "deserialize_number_from_string")]
@@ -145,36 +147,36 @@ pub struct PaginatedResponse<T> {
pub pagination: PaginationInfo,
}
-#[derive(Serialize, Deserialize)]
+#[derive(Serialize, OaSchema, Deserialize)]
pub struct PaginationInfo {
pub limit: u32,
pub offset: u32,
pub total: i64,
}
-#[derive(Serialize, Deserialize, Debug)]
+#[derive(OaSchema, Serialize, Deserialize, Debug)]
pub struct UpdateSpeakerRequest {
pub id: i64,
pub name: Option<String>,
pub metadata: Option<String>,
}
-#[derive(Serialize, Deserialize, Debug)]
+#[derive(OaSchema, Serialize, Deserialize, Debug)]
pub struct SearchSpeakersRequest {
pub name: Option<String>,
}
-#[derive(Serialize, Deserialize, Debug)]
+#[derive(OaSchema, Serialize, Deserialize, Debug)]
pub struct DeleteSpeakerRequest {
pub id: i64,
}
-#[derive(Deserialize)]
+#[derive(OaSchema, Deserialize)]
struct MarkAsHallucinationRequest {
speaker_id: i64,
}
-#[derive(Serialize, Deserialize, Debug)]
+#[derive(OaSchema, Serialize, Deserialize, Debug)]
#[serde(tag = "type", content = "content")]
pub enum ContentItem {
OCR(OCRContent),
@@ -182,7 +184,7 @@ pub enum ContentItem {
UI(UiContent),
}
-#[derive(Serialize, Deserialize, Debug)]
+#[derive(OaSchema, Serialize, Deserialize, Debug)]
pub struct OCRContent {
pub frame_id: i64,
pub text: String,
@@ -198,7 +200,7 @@ pub struct OCRContent {
pub focused: Option<bool>,
}
-#[derive(Serialize, Deserialize, Debug)]
+#[derive(OaSchema, Serialize, Deserialize, Debug)]
pub struct AudioContent {
pub chunk_id: i64,
pub transcription: String,
@@ -213,7 +215,7 @@ pub struct AudioContent {
pub end_time: Option<f64>,
}
-#[derive(Serialize, Deserialize, Debug)]
+#[derive(OaSchema, Serialize, Deserialize, Debug)]
pub struct UiContent {
pub id: i64,
pub text: String,
@@ -227,13 +229,13 @@ pub struct UiContent {
pub browser_url: Option<String>,
}
-#[derive(Serialize)]
+#[derive(OaSchema, Serialize)]
pub(crate) struct ListDeviceResponse {
name: String,
is_default: bool,
}
-#[derive(Serialize)]
+#[derive(OaSchema, Serialize)]
pub struct MonitorInfo {
pub id: u32,
pub name: String,
@@ -242,22 +244,22 @@ pub struct MonitorInfo {
pub is_default: bool,
}
-#[derive(Deserialize)]
+#[derive(OaSchema, Deserialize)]
pub struct AddTagsRequest {
tags: Vec<String>,
}
-#[derive(Serialize)]
+#[derive(OaSchema, Serialize)]
pub struct AddTagsResponse {
success: bool,
}
-#[derive(Deserialize)]
+#[derive(OaSchema, Deserialize)]
pub struct RemoveTagsRequest {
tags: Vec<String>,
}
-#[derive(Serialize)]
+#[derive(OaSchema, Serialize)]
pub struct RemoveTagsResponse {
success: bool,
}
@@ -267,7 +269,7 @@ fn default_limit() -> u32 {
20
}
-#[derive(Serialize, Deserialize)]
+#[derive(Serialize, OaSchema, Deserialize)]
pub struct HealthCheckResponse {
pub status: String,
pub status_code: u16,
@@ -281,12 +283,20 @@ pub struct HealthCheckResponse {
pub verbose_instructions: Option<String>,
}
+
+#[derive(OaSchema, Serialize, Deserialize)]
+pub struct SearchResponse {
+ pub data: Vec<ContentItem>,
+ pub pagination: PaginationInfo,
+}
+
// Update the search function
+#[oasgen]
pub(crate) async fn search(
Query(query): Query<SearchQuery>,
State(state): State<Arc<AppState>>,
) -> Result<
- JsonResponse<PaginatedResponse<ContentItem>>,
+ JsonResponse<SearchResponse>,
(StatusCode, JsonResponse<serde_json::Value>),
> {
info!(
@@ -423,7 +433,7 @@ pub(crate) async fn search(
}
info!("search completed: found {} results", total);
- Ok(JsonResponse(PaginatedResponse {
+ Ok(JsonResponse( SearchResponse {
data: content_items,
pagination: PaginationInfo {
limit: query.pagination.limit,
@@ -433,6 +443,7 @@ pub(crate) async fn search(
}))
}
+#[oasgen]
pub(crate) async fn api_list_audio_devices(
State(_state): State<Arc<AppState>>,
) -> Result<JsonResponse<Vec<ListDeviceResponse>>, (StatusCode, JsonResponse<serde_json::Value>)> {
@@ -478,6 +489,7 @@ pub(crate) async fn api_list_audio_devices(
}
}
+#[oasgen]
pub async fn api_list_monitors(
) -> Result<JsonResponse<Vec<MonitorInfo>>, (StatusCode, JsonResponse<serde_json::Value>)> {
let monitors = list_monitors().await;
@@ -512,11 +524,12 @@ pub async fn api_list_monitors(
}
}
+#[oasgen]
pub(crate) async fn add_tags(
State(state): State<Arc<AppState>>,
Path((content_type, id)): Path<(String, i64)>,
JsonResponse(payload): JsonResponse<AddTagsRequest>,
-) -> Result<JsonResponse<AddTagsResponse>, (StatusCode, JsonResponse<Value>)> {
+) -> Result<Json<AddTagsResponse>, (StatusCode, JsonResponse<Value>)> {
let content_type = match content_type.as_str() {
"vision" => TagContentType::Vision,
"audio" => TagContentType::Audio,
@@ -540,11 +553,12 @@ pub(crate) async fn add_tags(
}
}
+#[oasgen]
pub(crate) async fn remove_tags(
State(state): State<Arc<AppState>>,
Path((content_type, id)): Path<(String, i64)>,
JsonResponse(payload): JsonResponse<RemoveTagsRequest>,
-) -> Result<JsonResponse<RemoveTagsResponse>, (StatusCode, JsonResponse<Value>)> {
+) -> Result<Json<RemoveTagsResponse>, (StatusCode, JsonResponse<Value>)> {
let content_type = match content_type.as_str() {
"vision" => TagContentType::Vision,
"audio" => TagContentType::Audio,
@@ -568,6 +582,7 @@ pub(crate) async fn remove_tags(
}
}
+#[oasgen]
pub async fn health_check(State(state): State<Arc<AppState>>) -> JsonResponse<HealthCheckResponse> {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
@@ -679,36 +694,36 @@ pub async fn health_check(State(state): State<Arc<AppState>>) -> JsonResponse<He
})
}
// Request and response structs
-#[derive(Deserialize)]
+#[derive(OaSchema, Deserialize)]
struct DownloadPipeRequest {
url: String,
}
-#[derive(Deserialize)]
+#[derive(OaSchema, Deserialize)]
struct DownloadPipePrivateRequest {
url: String,
pipe_name: String,
pipe_id: String,
}
-#[derive(Deserialize)]
+#[derive(OaSchema, Deserialize)]
struct RunPipeRequest {
pipe_id: String,
}
-#[derive(Deserialize)]
+#[derive(OaSchema, Deserialize)]
struct UpdatePipeConfigRequest {
pipe_id: String,
config: serde_json::Value,
}
-#[derive(Deserialize)]
+#[derive(OaSchema, Deserialize)]
struct UpdatePipeVersionRequest {
pipe_id: String,
source: String,
}
-// Handler functions
+#[oasgen]
async fn download_pipe_handler(
State(state): State<Arc<AppState>>,
JsonResponse(payload): JsonResponse<DownloadPipeRequest>,
@@ -735,6 +750,7 @@ async fn download_pipe_handler(
}
}
+#[oasgen]
async fn download_pipe_private_handler(
State(state): State<Arc<AppState>>,
JsonResponse(payload): JsonResponse<DownloadPipePrivateRequest>,
@@ -764,6 +780,7 @@ async fn download_pipe_private_handler(
}
}
+#[oasgen]
async fn run_pipe_handler(
State(state): State<Arc<AppState>>,
JsonResponse(payload): JsonResponse<RunPipeRequest>,
@@ -797,6 +814,7 @@ async fn run_pipe_handler(
}
}
+#[oasgen]
async fn stop_pipe_handler(
State(state): State<Arc<AppState>>,
JsonResponse(payload): JsonResponse<RunPipeRequest>,
@@ -829,6 +847,7 @@ async fn stop_pipe_handler(
}
}
+#[oasgen]
async fn update_pipe_config_handler(
State(state): State<Arc<AppState>>,
JsonResponse(payload): JsonResponse<UpdatePipeConfigRequest>,
@@ -856,6 +875,7 @@ async fn update_pipe_config_handler(
}
}
+#[oasgen]
async fn update_pipe_version_handler(
State(state): State<Arc<AppState>>,
JsonResponse(payload): JsonResponse<UpdatePipeVersionRequest>,
@@ -883,6 +903,7 @@ async fn update_pipe_version_handler(
}
}
+#[oasgen]
async fn get_pipe_info_handler(
State(state): State<Arc<AppState>>,
Path(pipe_id): Path<String>,
@@ -903,6 +924,7 @@ async fn get_pipe_info_handler(
}
}
+#[oasgen]
async fn list_pipes_handler(State(state): State<Arc<AppState>>) -> JsonResponse<Value> {
let pipes = state.pipe_manager.list_pipes().await;
JsonResponse(json!({
@@ -911,7 +933,7 @@ async fn list_pipes_handler(State(state): State<Arc<AppState>>) -> JsonResponse<
}))
}
-pub struct Server {
+pub struct SCServer {
db: Arc<DatabaseManager>,
addr: SocketAddr,
// device_manager: Arc<DeviceManager>,
@@ -922,7 +944,7 @@ pub struct Server {
ui_monitoring_enabled: bool,
}
-impl Server {
+impl SCServer {
#[allow(clippy::too_many_arguments)]
pub fn new(
db: Arc<DatabaseManager>,
@@ -933,7 +955,7 @@ impl Server {
audio_disabled: bool,
ui_monitoring_enabled: bool,
) -> Self {
- Server {
+ SCServer {
db,
addr,
screenpipe_dir,
@@ -979,39 +1001,91 @@ impl Server {
},
});
- let app = create_router()
- .layer(ApiPluginLayer::new(api_plugin))
- .layer(
- CorsLayer::new()
- .allow_origin(Any)
- .allow_methods(Any)
- .allow_headers(Any)
- .expose_headers([
- axum::http::header::CONTENT_TYPE,
- axum::http::header::CACHE_CONTROL,
- ]), // Important for SSE
- )
- .layer(
- TraceLayer::new_for_http()
- .make_span_with(DefaultMakeSpan::new().include_headers(true)),
- )
- .with_state(app_state);
-
- info!("Server starting on {}", self.addr);
+ let cors = CorsLayer::new()
+ .allow_origin(Any)
+ .allow_methods(Any)
+ .allow_headers(Any)
+ .expose_headers([
+ axum::http::header::CONTENT_TYPE,
+ axum::http::header::CACHE_CONTROL,
+ ]);
+
+ // Create the OpenAPI server
+ let server = Server::axum()
+ .get("/search", search)
+ .get("/audio/list", api_list_audio_devices)
+ .get("/vision/list", api_list_monitors)
+ .post("/tags/:content_type/:id", add_tags)
+ .delete("/tags/:content_type/:id", remove_tags)
+ .get("/pipes/info/:pipe_id", get_pipe_info_handler)
+ .get("/pipes/list", list_pipes_handler)
+ .post("/pipes/download", download_pipe_handler)
+ .post("/pipes/download-private", download_pipe_private_handler)
+ .post("/pipes/enable", run_pipe_handler)
+ .post("/pipes/disable", stop_pipe_handler)
+ .post("/pipes/update", update_pipe_config_handler)
+ .post("/pipes/update-version", update_pipe_version_handler)
+ .post("/pipes/delete", delete_pipe_handler)
+ .post("/pipes/purge", purge_pipe_handler)
+ .get("/frames/:frame_id", get_frame_data)
+ .get("/health", health_check)
+ .post("/raw_sql", execute_raw_sql)
+ .post("/add", add_to_database)
+ .get("/speakers/unnamed", get_unnamed_speakers_handler)
+ .post("/speakers/update", update_speaker_handler)
+ .get("/speakers/search", search_speakers_handler)
+ .post("/speakers/delete", delete_speaker_handler)
+ .post("/speakers/hallucination", mark_as_hallucination_handler)
+ .post("/speakers/merge", merge_speakers_handler)
+ .get("/speakers/similar", get_similar_speakers_handler)
+ .post("/experimental/frames/merge", merge_frames_handler)
+ .get("/experimental/validate/media", validate_media_handler)
+ // .post("/audio/start", start_audio_device)
+ // .post("/audio/stop", stop_audio_device)
+ .get("/semantic-search", semantic_search_handler)
+ .get("/pipes/build-status/:pipe_id", get_pipe_build_status)
+ .get("/search/keyword", keyword_search_handler)
+ .post("/v1/embeddings", create_embeddings)
+ // .post("/vision/start", start_vision_device)
+ // .post("/vision/stop", stop_vision_device)
+ // .post("/audio/restart", restart_audio_devices)
+ // .post("/vision/restart", restart_vision_devices)
+ .route_yaml_spec("/openapi.yaml")
+ .route_json_spec("/openapi.json")
+ .freeze();
+
+ // Build the main router with all routes
+ let app = Router::new()
+ .merge(server.into_router())
+ // NOTE: websockerts and sse is not supported by openapi so we move it down here
+ .route("/stream/frames", get(stream_frames_handler))
+ .route("/ws/events", get(ws_events_handler))
+ .route("/ws/health", get(ws_health_handler))
+ .route("/frames/export", get(handle_video_export_ws))
+ .with_state(app_state)
+ .layer(cors)
+ .layer(TraceLayer::new_for_http().make_span_with(DefaultMakeSpan::default()));
+
+ #[cfg(feature = "experimental")]
+ let app = app.route("/experimental/input_control", post(input_control_handler));
+
+ // Create the listener
+ let listener = TcpListener::bind(&self.addr).await?;
+ info!("Server listening on {}", self.addr);
+
+ // Start serving
+ serve(
+ listener,
+ app.into_make_service_with_connect_info::<SocketAddr>(),
+ )
+ .await
+ .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?;
- match serve(TcpListener::bind(self.addr).await?, app.into_make_service()).await {
- Ok(_) => {
- info!("Server stopped gracefully");
- Ok(())
- }
- Err(e) => {
- error!("Server error: {}", e);
- Err(e)
- }
- }
+ Ok(())
}
}
+#[oasgen]
async fn merge_frames_handler(
State(state): State<Arc<AppState>>,
JsonResponse(payload): JsonResponse<MergeVideosRequest>,
@@ -1030,6 +1104,7 @@ async fn merge_frames_handler(
}
}
+#[oasgen]
async fn validate_media_handler(
State(_state): State<Arc<AppState>>,
Query(params): Query<ValidateMediaParams>,
@@ -1043,11 +1118,12 @@ async fn validate_media_handler(
}
}
-#[derive(Deserialize)]
+#[derive(OaSchema, Deserialize)]
struct RawSqlQuery {
query: String,
}
+#[oasgen]
async fn execute_raw_sql(
State(state): State<Arc<AppState>>,
JsonResponse(payload): JsonResponse<RawSqlQuery>,
@@ -1064,26 +1140,26 @@ async fn execute_raw_sql(
}
}
-#[derive(Deserialize)]
+#[derive(OaSchema, Deserialize)]
pub struct AddContentRequest {
pub device_name: String, // Moved device_name to the top level
pub content: AddContentData, // The actual content (either Frame or Transcription)
}
-#[derive(Deserialize)]
+#[derive(OaSchema, Deserialize)]
pub struct AddContentData {
pub content_type: String,
pub data: ContentData,
}
-#[derive(Deserialize)]
+#[derive(OaSchema, Deserialize)]
#[serde(untagged)]
pub enum ContentData {
Frames(Vec<FrameContent>),
Transcription(AudioTranscription),
}
-#[derive(Deserialize)]
+#[derive(OaSchema, Deserialize)]
pub struct FrameContent {
pub file_path: String,
pub timestamp: Option<DateTime<Utc>>,
@@ -1093,7 +1169,7 @@ pub struct FrameContent {
pub tags: Option<Vec<String>>,
}
-#[derive(Serialize, Deserialize, Debug)]
+#[derive(Serialize, OaSchema, Deserialize, Debug)]
pub struct OCRResult {
pub text: String,
pub text_json: Option<String>,
@@ -1101,13 +1177,13 @@ pub struct OCRResult {
pub focused: Option<bool>,
}
-#[derive(Deserialize)]
+#[derive(OaSchema, Deserialize)]
pub struct AudioTranscription {
pub transcription: String,
pub transcription_engine: String,
}
-#[derive(Serialize)]
+#[derive(OaSchema, Serialize)]
pub struct AddContentResponse {
pub success: bool,
pub message: Option<String>,
@@ -1210,10 +1286,11 @@ async fn add_transcription_to_db(
Ok(())
}
+#[oasgen]
pub(crate) async fn add_to_database(
State(state): State<Arc<AppState>>,
Json(payload): Json<AddContentRequest>,
-) -> Result<JsonResponse<AddContentResponse>, (StatusCode, JsonResponse<Value>)> {
+) -> Result<Json<AddContentResponse>, (StatusCode, Json<serde_json::Value>)> {
let device_name = payload.device_name.clone();
let mut success_messages = Vec::new();
@@ -1474,7 +1551,7 @@ impl From<TimeSeriesFrame> for StreamTimeSeriesResponse {
}
}
-#[derive(Deserialize, Debug)]
+#[derive(OaSchema, Deserialize, Debug)]
pub struct GetUnnamedSpeakersRequest {
limit: u32,
offset: u32,
@@ -1490,7 +1567,7 @@ fn default_speaker_ids() -> Option<Vec<i64>> {
None
}
-#[derive(Deserialize, Debug)]
+#[derive(OaSchema, Deserialize, Debug)]
pub struct GetSimilarSpeakersRequest {
speaker_id: i64,
limit: u32,
@@ -1511,6 +1588,7 @@ where
.map(Some)
}
+#[oasgen]
async fn get_unnamed_speakers_handler(
State(state): State<Arc<AppState>>,
Query(request): Query<GetUnnamedSpeakersRequest>,
@@ -1544,6 +1622,7 @@ async fn get_unnamed_speakers_handler(
Ok(JsonResponse(speakers))
}
+#[oasgen]
async fn update_speaker_handler(
State(state): State<Arc<AppState>>,
Json(payload): Json<UpdateSpeakerRequest>,
@@ -1577,6 +1656,7 @@ async fn update_speaker_handler(
))
}
+#[oasgen]
async fn search_speakers_handler(
State(state): State<Arc<AppState>>,
Query(request): Query<SearchSpeakersRequest>,
@@ -1587,6 +1667,7 @@ async fn search_speakers_handler(
))
}
+#[oasgen]
async fn delete_speaker_handler(
State(state): State<Arc<AppState>>,
Json(payload): Json<DeleteSpeakerRequest>,
@@ -1625,6 +1706,7 @@ async fn delete_speaker_handler(
Ok(JsonResponse(json!({"success": true})))
}
+#[oasgen]
async fn mark_as_hallucination_handler(
State(state): State<Arc<AppState>>,
Json(payload): Json<MarkAsHallucinationRequest>,
@@ -1640,6 +1722,7 @@ async fn mark_as_hallucination_handler(
Ok(JsonResponse(json!({"success": true})))
}
+#[oasgen]
async fn merge_speakers_handler(
State(state): State<Arc<AppState>>,
Json(payload): Json<MergeSpeakersRequest>,
@@ -1661,6 +1744,7 @@ async fn merge_speakers_handler(
Ok(JsonResponse(json!({"success": true})))
}
+#[oasgen]
async fn get_similar_speakers_handler(
State(state): State<Arc<AppState>>,
Query(request): Query<GetSimilarSpeakersRequest>,
@@ -1681,7 +1765,7 @@ async fn get_similar_speakers_handler(
Ok(JsonResponse(similar_speakers))
}
-// #[derive(Deserialize)]
+// #[derive(OaSchema, Deserialize)]
// pub struct AudioDeviceControlRequest {
// device_name: String,
// #[serde(default)]
@@ -1784,18 +1868,19 @@ pub struct AudioDeviceControlResponse {
// }))
// }
-#[derive(Deserialize)]
+#[derive(OaSchema, Deserialize)]
struct EventsQuery {
images: Option<bool>,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, OaSchema, Deserialize)]
struct SemanticSearchQuery {
text: String,
limit: Option<u32>,
threshold: Option<f32>,
}
+#[oasgen]
async fn semantic_search_handler(
Query(query): Query<SemanticSearchQuery>,
State(state): State<Arc<AppState>>,
@@ -1840,7 +1925,7 @@ async fn semantic_search_handler(
}
}
-#[derive(Serialize, Deserialize)]
+#[derive(Serialize, OaSchema, Deserialize)]
pub struct VisionDeviceControlRequest {
device_id: u32,
}
@@ -2010,77 +2095,6 @@ async fn handle_health_socket(mut socket: WebSocket, state: Arc<AppState>) {
debug!("WebSocket connection closed gracefully");
}
-pub fn create_router() -> Router<Arc<AppState>> {
- let cors = CorsLayer::new()
- .allow_origin(Any)
- .allow_methods(Any)
- .allow_headers(Any)
- .expose_headers([
- axum::http::header::CONTENT_TYPE,
- axum::http::header::CACHE_CONTROL,
- ]); // Important for SSE
-
- #[allow(unused_mut)]
- let mut router = Router::new()
- .route("/search", get(search))
- .route("/audio/list", get(api_list_audio_devices))
- .route("/vision/list", get(api_list_monitors))
- .route(
- "/tags/:content_type/:id",
- post(add_tags).delete(remove_tags),
- )
- .route("/pipes/info/:pipe_id", get(get_pipe_info_handler))
- .route("/pipes/list", get(list_pipes_handler))
- .route("/pipes/download", post(download_pipe_handler))
- .route(
- "/pipes/download-private",
- post(download_pipe_private_handler),
- )
- .route("/pipes/enable", post(run_pipe_handler))
- .route("/pipes/disable", post(stop_pipe_handler))
- .route("/pipes/update", post(update_pipe_config_handler))
- .route("/pipes/update-version", post(update_pipe_version_handler))
- .route("/pipes/delete", post(delete_pipe_handler))
- .route("/pipes/purge", post(purge_pipe_handler))
- .route("/health", get(health_check))
- .route("/ws/health", get(ws_health_handler))
- .route("/raw_sql", post(execute_raw_sql))
- .route("/add", post(add_to_database))
- .route("/stream/frames", get(stream_frames_handler))
- .route("/speakers/unnamed", get(get_unnamed_speakers_handler))
- .route("/speakers/update", post(update_speaker_handler))
- .route("/speakers/search", get(search_speakers_handler))
- .route("/speakers/delete", post(delete_speaker_handler))
- .route(
- "/speakers/hallucination",
- post(mark_as_hallucination_handler),
- )
- .route("/speakers/merge", post(merge_speakers_handler))
- .route("/speakers/similar", get(get_similar_speakers_handler))
- .route("/experimental/frames/merge", post(merge_frames_handler))
- .route("/experimental/validate/media", get(validate_media_handler))
- // .route("/audio/start", post(start_audio_device))
- // .route("/audio/stop", post(stop_audio_device))
- .route("/ws/events", get(ws_events_handler))
- .route("/semantic-search", get(semantic_search_handler))
- .route("/frames/:frame_id", get(get_frame_data))
- .route("/pipes/build-status/:pipe_id", get(get_pipe_build_status))
- .route("/search/keyword", get(keyword_search_handler))
- .route("/v1/embeddings", axum::routing::post(create_embeddings))
- // .route("/vision/start", post(start_vision_device))
- // .route("/vision/stop", post(stop_vision_device))
- // .route("/audio/restart", post(restart_audio_devices))
- // .route("/vision/restart", post(restart_vision_devices))
- .route("/frames/export", get(handle_video_export_ws))
- .layer(cors);
-
- #[cfg(feature = "experimental")]
- {
- router = router.route("/experimental/input_control", post(input_control_handler));
- }
- router
-}
-
#[derive(Debug, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct VideoExportRequest {
@@ -2372,10 +2386,11 @@ async fn get_pipe_build_status(
Ok(JsonResponse(json!({ "buildStatus": build_status })))
}
+#[oasgen]
async fn keyword_search_handler(
Query(query): Query<KeywordSearchRequest>,
State(state): State<Arc<AppState>>,
-) -> Result<JsonResponse<Vec<SearchMatch>>, (StatusCode, JsonResponse<Value>)> {
+) -> Result<Json<Vec<SearchMatch>>, (StatusCode, JsonResponse<Value>)> {
let matches = state
.db
.search_with_text_positions(
@@ -2407,7 +2422,7 @@ where
Ok(s.map(|s| s.split(',').map(String::from).collect()))
}
-#[derive(Deserialize)]
+#[derive(OaSchema, Deserialize)]
pub struct KeywordSearchRequest {
query: String,
#[serde(default = "default_limit")]
@@ -2427,10 +2442,11 @@ pub struct KeywordSearchRequest {
app_names: Option<Vec<String>>,
}
+#[oasgen]
pub async fn get_frame_data(
State(state): State<Arc<AppState>>,
Path(frame_id): Path<i64>,
-) -> Result<impl IntoResponse, (StatusCode, JsonResponse<Value>)> {
+) -> Result<Response<Body>, (StatusCode, JsonResponse<Value>)> {
let start_time = Instant::now();
match timeout(Duration::from_secs(5), async {
@@ -2729,64 +2745,59 @@ async fn stream_frames_handler(
ws.on_upgrade(move |socket| handle_stream_frames_socket(socket, state))
}
-// Add this new handler function
+#[oasgen]
pub async fn delete_pipe_handler(
State(state): State<Arc<AppState>>,
Json(request): Json<DeletePipeRequest>,
-) -> impl IntoResponse {
+) -> Result<JsonResponse<Value>, (StatusCode, JsonResponse<Value>)> {
match state.pipe_manager.delete_pipe(&request.pipe_id).await {
- Ok(_) => (
- StatusCode::OK,
- Json(json!({
- "success": true,
- "message": "pipe deleted successfully"
- })),
- ),
+ Ok(_) => Ok(JsonResponse(json!({
+ "success": true,
+ "message": "pipe deleted successfully"
+ }))),
Err(e) => {
error!("failed to delete pipe: {}", e);
- (
+ Err((
StatusCode::INTERNAL_SERVER_ERROR,
- Json(json!({
- "success": false,
- "error": format!("failed to delete pipe: {}", e)
+ JsonResponse(json!({
+ "success": false,
+ "error": format!("failed to delete pipe: {}", e)
})),
- )
+ ))
}
}
}
+#[oasgen]
pub async fn purge_pipe_handler(
State(state): State<Arc<AppState>>,
Json(_request): Json<PurgePipeRequest>,
-) -> impl IntoResponse {
+) -> Result<JsonResponse<Value>, (StatusCode, JsonResponse<Value>)> {
match state.pipe_manager.purge_pipes().await {
- Ok(_) => (
- StatusCode::OK,
- Json(json!({
- "success": true,
- "message": "pipes purged successfully"
- })),
- ),
+ Ok(_) => Ok(JsonResponse(json!({
+ "success": true,
+ "message": "pipes purged successfully"
+ }))),
Err(e) => {
error!("failed to purge pipes: {}", e);
- (
+ Err((
StatusCode::INTERNAL_SERVER_ERROR,
- Json(json!({
- "success": false,
- "error": format!("failed to purge pipes: {}", e)
- })),
- )
+ JsonResponse(json!({
+ "success": false,
+ "error": format!("failed to purge pipes: {}", e)
+ }))
+ ))
}
}
}
// Add this struct for the request payload
-#[derive(Debug, Deserialize)]
+#[derive(Debug, OaSchema, Deserialize)]
pub struct DeletePipeRequest {
pipe_id: String,
}
-#[derive(Deserialize, Debug)]
+#[derive(OaSchema, Deserialize, Debug)]
struct MergeSpeakersRequest {
speaker_to_keep_id: i64,
speaker_to_merge_id: i64,
@@ -2799,7 +2810,7 @@ pub struct RestartAudioDevicesResponse {
restarted_devices: Vec<String>,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, OaSchema, Deserialize)]
pub struct PurgePipeRequest {}
// async fn restart_audio_devices(
diff --git a/screenpipe-server/src/video_utils.rs b/screenpipe-server/src/video_utils.rs
index 22e2b8dce..4f0b4c540 100644
--- a/screenpipe-server/src/video_utils.rs
+++ b/screenpipe-server/src/video_utils.rs
@@ -3,6 +3,7 @@ use base64::{engine::general_purpose, Engine as _};
use chrono::NaiveDateTime;
use chrono::{DateTime, Utc};
use image::DynamicImage;
+use oasgen::OaSchema;
use screenpipe_core::find_ffmpeg_path;
use serde::{Deserialize, Serialize};
use std::path::Path;
@@ -91,17 +92,17 @@ pub async fn extract_frame(file_path: &str, offset_index: i64) -> Result<String>
Ok(general_purpose::STANDARD.encode(frame_data))
}
-#[derive(Deserialize)]
+#[derive(OaSchema, Deserialize)]
pub struct MergeVideosRequest {
pub video_paths: Vec<String>,
}
-#[derive(Serialize)]
+#[derive(OaSchema, Serialize)]
pub struct MergeVideosResponse {
video_path: String,
}
-#[derive(Deserialize)]
+#[derive(OaSchema, Deserialize)]
pub struct ValidateMediaParams {
pub file_path: String,
}