Skip to content

A command-line tool to convert handwritten notes to markdown files

feat: added dynamic database property configuration

Tejas Raskar82d1f9945742
diff --git a/src/clients/notion_client.rs b/src/clients/notion_client.rs
index 70dd2bd..c70118f 100644
--- a/src/clients/notion_client.rs
+++ b/src/clients/notion_client.rs
@@ -1,6 +1,10 @@
+use std::collections::HashMap;
+
+use anyhow::Result;
+use colored::Colorize;
use comrak::Arena;
use notion_client::objects::block::Block;
-use reqwest::{Client, StatusCode};
+use reqwest::Client;
use serde::{Deserialize, Serialize};
use crate::{error::NotedError, notion::converter};
@@ -59,6 +63,65 @@ pub struct NotionResponse {
pub url: String,
}
+#[derive(Deserialize, Debug)]
+pub struct NotionDatabase {
+ pub properties: HashMap<String, DatabaseProperty>,
+}
+
+#[derive(Deserialize, Debug)]
+pub struct DatabaseProperty {
+ pub id: String,
+ pub name: String,
+ #[serde(flatten)]
+ pub type_specific_config: PropertyType,
+}
+
+#[derive(Deserialize, Debug)]
+#[serde(tag = "type")]
+#[serde(rename_all = "snake_case")]
+pub enum PropertyType {
+ Title(EmptyStruct),
+ RichText(EmptyStruct),
+ Number(NumberStruct),
+ Select { select: SelectStruct },
+ MultiSelect { multi_select: SelectStruct },
+ Date(EmptyStruct),
+ Checkbox(EmptyStruct),
+ People(EmptyStruct),
+ Files(EmptyStruct),
+ Url(EmptyStruct),
+ Email(EmptyStruct),
+ CreatedTime(EmptyStruct),
+ CreatedBy(EmptyStruct),
+ LastEditedTime(EmptyStruct),
+ LastEditedBy(EmptyStruct),
+}
+
+#[derive(Deserialize, Debug)]
+pub struct SelectStruct {
+ pub options: Vec<DatabaseSelectOption>,
+}
+
+#[derive(Deserialize, Debug, Clone)]
+pub struct DatabaseSelectOption {
+ pub id: String,
+ pub name: String,
+ pub color: String,
+}
+
+#[derive(Deserialize, Debug)]
+pub struct NumberStruct {
+ pub number: NumberFormat,
+}
+
+#[derive(Deserialize, Debug)]
+pub struct NumberFormat {
+ pub format: String,
+}
+
+#[derive(Deserialize, Debug)]
+pub struct EmptyStruct {}
+
#[derive(Deserialize, Debug)]
pub struct NotionError {
pub message: String,
@@ -80,6 +143,33 @@ impl NotionClient {
}
}
+ pub async fn get_database_schema(&self) -> Result<NotionDatabase, NotedError> {
+ let url = format!("https://api.notion.com/v1/databases/{}", self.database_id);
+ let response = self
+ .client
+ .get(url)
+ .header("Authorization", format!("Bearer {}", self.api_key))
+ .header("Notion-Version", "2022-06-28")
+ .send()
+ .await?;
+
+ let status = response.status();
+ let response_body = response.text().await?;
+ if status.is_success() {
+ let notion_database: NotionDatabase = serde_json::from_str(&response_body)
+ .map_err(|e| NotedError::ResponseDecodeError(e.to_string()))?;
+ Ok(notion_database)
+ } else {
+ let error_response: NotionError = serde_json::from_str(&response_body)
+ .map_err(|e| NotedError::ResponseDecodeError(e.to_string()))?;
+ Err(NotedError::ApiError(format!(
+ "Notion API Error ({}): {}",
+ status,
+ error_response.message.red()
+ )))
+ }
+ }
+
pub async fn create_notion_page(
&self,
title: &str,
diff --git a/src/config.rs b/src/config.rs
index 4e8efdc..792010f 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -17,6 +17,15 @@ pub struct Config {
pub struct NotionConfig {
pub api_key: String,
pub database_id: String,
+ #[serde(default)]
+ pub properties: Vec<NotionPropertyConfig>,
+}
+
+#[derive(Serialize, Deserialize, Debug, Default, Clone)]
+pub struct NotionPropertyConfig {
+ pub name: String,
+ pub property_type: String,
+ pub default_value: serde_json::Value,
}
#[derive(Serialize, Deserialize, Debug, Default)]
diff --git a/src/main.rs b/src/main.rs
index 6bd8b78..6fd7f93 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -14,6 +14,7 @@ use colored::*;
use config::{ClaudeConfig, Config, GeminiConfig, OllamaConfig};
use dialoguer::Confirm;
use dialoguer::Input;
+use dialoguer::MultiSelect;
use dialoguer::Select;
use dialoguer::{Password, theme::ColorfulTheme};
use error::NotedError;
@@ -23,6 +24,7 @@ use indicatif::ProgressStyle;
use crate::clients::claude_client::ClaudeClient;
use crate::clients::gemini_client::GeminiClient;
use crate::clients::notion_client::NotionClient;
+use crate::clients::notion_client::PropertyType;
use crate::clients::ollama_client::OllamaClient;
use crate::clients::openai_client::OpenAIClient;
use crate::config::NotionConfig;
@@ -293,24 +295,181 @@ async fn run() -> Result<(), NotedError> {
// notion
let is_notion = Confirm::with_theme(&ColorfulTheme::default())
.with_prompt("Do you want to configure Notion to save your notes there?")
- .default(false)
.interact()?;
if is_notion {
let api_key = Password::with_theme(&ColorfulTheme::default())
.with_prompt("Enter your Notion API key: ")
.interact()?;
- let database_id = Input::with_theme(&ColorfulTheme::default())
+ let database_id = Password::with_theme(&ColorfulTheme::default())
.with_prompt("Enter your Notion Database ID: ")
- .default("".to_string())
.interact()?;
- let mut config = Config::load()?;
- config.notion = Some(NotionConfig {
- api_key,
- database_id,
- });
- config.save()?;
+ let spinner = ProgressBar::new_spinner();
+ spinner.set_style(
+ ProgressStyle::default_spinner()
+ .template("{spinner:.cyan} {msg}")
+ .unwrap(),
+ );
+ spinner.set_message("Fetching Notion database schema...");
+ spinner.enable_steady_tick(std::time::Duration::from_millis(100));
+
+ let client = NotionClient::new(api_key.clone(), database_id.clone());
+ let schema_result = client.get_database_schema().await;
+ spinner.finish_and_clear();
+ match schema_result {
+ Ok(schema) => {
+ let properties: Vec<_> = schema
+ .properties
+ .into_iter()
+ .filter(|(_name, property)| match &property.type_specific_config {
+ PropertyType::Select { .. }
+ | PropertyType::MultiSelect { .. }
+ | PropertyType::RichText(_)
+ | PropertyType::Number(_)
+ | PropertyType::Date(_)
+ | PropertyType::Checkbox(_) => true,
+
+ _ => false,
+ })
+ .collect();
+
+ let mut default_properties = Vec::new();
+ if properties.is_empty() {
+ println!(
+ "{}",
+ "No user configurable properties found in this database."
+ .yellow()
+ );
+ } else {
+ println!("Enter the default values for the following properties: ");
+ }
+ for (name, property) in &properties {
+ match &property.type_specific_config {
+ PropertyType::MultiSelect { multi_select } => {
+ let options: Vec<_> = multi_select
+ .options
+ .iter()
+ .map(|option| option.name.clone())
+ .collect();
+
+ let selections =
+ MultiSelect::with_theme(&ColorfulTheme::default())
+ .with_prompt(format!(
+ "Select default options for '{}' (press Space to select and Enter to confirm)",
+ name
+ ))
+ .items(&options)
+ .interact()?;
+ let selected_names: Vec<String> = selections
+ .iter()
+ .map(|&i| options[i].clone())
+ .collect();
+ let prop_config = config::NotionPropertyConfig {
+ name: name.clone(),
+ property_type: "multi_select".to_string(),
+ default_value: serde_json::json!(selected_names),
+ };
+ default_properties.push(prop_config);
+ }
+ PropertyType::Select { select } => {
+ let options: Vec<_> = select
+ .options
+ .iter()
+ .map(|option| option.name.clone())
+ .collect();
+ let selection = Select::with_theme(&ColorfulTheme::default())
+ .with_prompt(format!("Select default option for '{}' (press Space to select and Enter to confirm)", name))
+ .items(&options)
+ .interact()?;
+ let selected_name = options[selection].clone();
+ let prop_config = config::NotionPropertyConfig {
+ name: name.clone(),
+ property_type: "select".to_string(),
+ default_value: serde_json::json!(selected_name),
+ };
+ default_properties.push(prop_config);
+ }
+ PropertyType::RichText(_) => {
+ let default_value: String =
+ Input::with_theme(&ColorfulTheme::default())
+ .with_prompt(format!("Default text for '{}'", name))
+ .interact_text()?;
+ let prop_config = config::NotionPropertyConfig {
+ name: name.clone(),
+ property_type: "rich_text".to_string(),
+ default_value: serde_json::json!(default_value),
+ };
+ default_properties.push(prop_config);
+ }
+ PropertyType::Checkbox(_) => {
+ let checked =
+ Confirm::with_theme(&ColorfulTheme::default())
+ .with_prompt(format!(
+ "Should '{}' be checked by default?",
+ name
+ ))
+ .interact()?;
+ let prop_config = config::NotionPropertyConfig {
+ name: name.clone(),
+ property_type: "checkbox".to_string(),
+ default_value: serde_json::json!(checked),
+ };
+ default_properties.push(prop_config);
+ }
+
+ PropertyType::Date(_) => {
+ let default_value: String =
+ Input::with_theme(&ColorfulTheme::default())
+ .with_prompt(format!(
+ "Default date for '{}' (YYYY-MM-DD)",
+ name
+ ))
+ .interact_text()?;
+ let prop_config = config::NotionPropertyConfig {
+ name: name.clone(),
+ property_type: "date".to_string(),
+ default_value: serde_json::json!(default_value),
+ };
+ default_properties.push(prop_config);
+ }
+
+ PropertyType::Number(_) => {
+ let default_value: f64 =
+ Input::with_theme(&ColorfulTheme::default())
+ .with_prompt(format!(
+ "Default number for '{}'",
+ name
+ ))
+ .interact()?;
+ let prop_config = config::NotionPropertyConfig {
+ name: name.clone(),
+ property_type: "number".to_string(),
+ default_value: serde_json::json!(default_value),
+ };
+
+ default_properties.push(prop_config);
+ }
+ _ => {
+ println!(
+ "{} Property '{}' is not supported for default configuration.",
+ "✖".red(),
+ name
+ );
+ }
+ }
+ }
+
+ let mut config = Config::load()?;
+ config.notion = Some(NotionConfig {
+ api_key,
+ database_id,
+ properties: default_properties,
+ });
+ config.save()?;
+ }
+ Err(e) => eprintln!("{}", e),
+ }
}
println!(
"{}",