aboutsummaryrefslogtreecommitdiff
path: root/src/notion.rs
blob: 4dd7c5e9a5207f037bb030b9b00f9a974b80351b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
use serde::Deserialize;

const NOTION_API_VERSION: &str = "2022-06-28";

#[derive(Deserialize)]
pub struct QueryResponse {
  pub results:  Vec<Page>,
  pub has_more: bool,
}

#[derive(Deserialize)]
pub struct Page {
  pub id:         String,
  pub properties: serde_json::Value,
}

#[derive(Deserialize)]
pub struct BlockChildrenResponse {
  pub results:  Vec<Block>,
  pub has_more: bool,
}

#[derive(Deserialize)]
pub struct Block {
  #[serde(rename = "type")]
  pub kind:    String,
  #[serde(flatten)]
  pub content: serde_json::Value,
  pub id:      String,
}

pub fn extract_title(properties: &serde_json::Value, field: &str) -> String {
  properties[field]["title"]
    .as_array()
    .and_then(|rich_text_array| rich_text_array.first())
    .and_then(|rich_text_element| rich_text_element["plain_text"].as_str())
    .unwrap_or("")
    .to_string()
}

pub fn extract_rich_text(
  properties: &serde_json::Value,
  field: &str,
) -> String {
  properties[field]["rich_text"]
    .as_array()
    .map(|rich_text_array| {
      rich_text_array
        .iter()
        .filter_map(|rich_text_element| {
          rich_text_element["plain_text"].as_str()
        })
        .collect::<Vec<_>>()
        .join("")
    })
    .unwrap_or_default()
}

pub fn extract_number(
  properties: &serde_json::Value,
  field: &str,
) -> Option<u8> {
  extract_non_negative_whole_number(properties, field)
    .and_then(|number_value| u8::try_from(number_value).ok())
}

fn extract_non_negative_whole_number(
  properties: &serde_json::Value,
  field: &str,
) -> Option<u64> {
  let number_value = &properties[field]["number"];

  number_value.as_u64().or_else(|| {
    number_value.as_f64().and_then(|floating_value| {
      if !floating_value.is_finite() || floating_value < 0.0 {
        return None;
      }

      let rounded_value = floating_value.round();
      let is_whole_number =
        (floating_value - rounded_value).abs() <= f64::EPSILON;

      if !is_whole_number {
        return None;
      }

      format!("{rounded_value:.0}").parse::<u64>().ok()
    })
  })
}

pub fn extract_date(properties: &serde_json::Value, field: &str) -> String {
  properties[field]["date"]["start"].as_str().unwrap_or("").to_string()
}

pub fn extract_relation_ids(
  properties: &serde_json::Value,
  field: &str,
) -> Vec<String> {
  properties[field]["relation"]
    .as_array()
    .map(|relation_array| {
      relation_array
        .iter()
        .filter_map(|relation_entry| {
          relation_entry["id"].as_str().map(String::from)
        })
        .collect()
    })
    .unwrap_or_default()
}

pub fn extract_checkbox(properties: &serde_json::Value, field: &str) -> bool {
  properties[field]["checkbox"].as_bool().unwrap_or(false)
}

pub fn format_notion_date(iso_date: &str) -> String {
  chrono::NaiveDate::parse_from_str(iso_date, "%Y-%m-%d").map_or_else(
    |_| iso_date.to_string(),
    |date| date.format("%B %-d, %Y").to_string(),
  )
}

pub fn extract_block_plain_text(block: &Block) -> String {
  let block_content = &block.content[&block.kind];

  block_content["rich_text"]
    .as_array()
    .map(|rich_text_array| {
      rich_text_array
        .iter()
        .filter_map(|rich_text_element| {
          rich_text_element["plain_text"].as_str()
        })
        .collect::<Vec<_>>()
        .join("")
    })
    .unwrap_or_default()
}

pub fn query_database(
  http_client: &reqwest::blocking::Client,
  api_key: &str,
  database_identifier: &str,
) -> Result<Vec<Page>, reqwest::Error> {
  let mut all_pages = Vec::new();
  let mut start_cursor: Option<String> = None;

  loop {
    let mut request_body = serde_json::json!({});

    if let Some(ref cursor) = start_cursor {
      request_body["start_cursor"] = serde_json::json!(cursor);
    }

    let response = http_client
      .post(format!(
        "https://api.notion.com/v1/databases/{database_identifier}/query"
      ))
      .header("Authorization", format!("Bearer {api_key}"))
      .header("Notion-Version", NOTION_API_VERSION)
      .json(&request_body)
      .send()?
      .json::<QueryResponse>()?;
    let has_more = response.has_more;

    all_pages.extend(response.results);

    if !has_more {
      break;
    }

    start_cursor = all_pages.last().map(|last_page| last_page.id.clone());
  }

  Ok(all_pages)
}

pub fn fetch_page_content(
  http_client: &reqwest::blocking::Client,
  api_key: &str,
  page_identifier: &str,
) -> Result<String, reqwest::Error> {
  let mut all_lines = Vec::new();
  let mut start_cursor: Option<String> = None;

  loop {
    let mut request_url = format!(
      "https://api.notion.com/v1/blocks/{page_identifier}/children?page_size=100"
    );

    if let Some(ref cursor) = start_cursor {
      request_url.push_str(&format!("&start_cursor={cursor}"));
    }

    let response = http_client
      .get(&request_url)
      .header("Authorization", format!("Bearer {api_key}"))
      .header("Notion-Version", NOTION_API_VERSION)
      .send()?
      .json::<BlockChildrenResponse>()?;
    let has_more = response.has_more;

    for block in &response.results {
      let line = match block.kind.as_str() {
        "heading_1" => format!("# {}", extract_block_plain_text(block)),
        "heading_2" => format!("## {}", extract_block_plain_text(block)),
        "heading_3" => format!("### {}", extract_block_plain_text(block)),
        "bulleted_list_item" | "numbered_list_item" => {
          format!("* {}", extract_block_plain_text(block))
        }
        "quote" => format!("> {}", extract_block_plain_text(block)),
        "code" => format!("```\n{}\n```", extract_block_plain_text(block)),
        "divider" => "---".to_string(),
        _ => extract_block_plain_text(block),
      };

      all_lines.push(line);
    }

    if !has_more {
      break;
    }

    start_cursor =
      response.results.last().map(|last_block| last_block.id.clone());
  }

  Ok(all_lines.join("\n"))
}

#[cfg(test)]
mod tests {
  use {super::extract_checkbox, serde_json::json};

  #[test]
  fn extract_checkbox_true() {
    let properties = json!({
      "Hidden": {
        "checkbox": true
      }
    });

    assert!(extract_checkbox(&properties, "Hidden"));
  }

  #[test]
  fn extract_checkbox_false_when_missing() {
    let properties = json!({
      "Title": {
        "title": []
      }
    });

    assert!(!extract_checkbox(&properties, "Hidden"));
  }
}