forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

import.rs350 lines, 13.4 KiBHistoryRawDownload
1//! Markdown import: POST /import/file creates one note from one file, and GET /import is
2//! the page that picks files or a folder and sends them one at a time.
3//!
4//! The browser sends each path with the selected root folder already stripped. A path
5//! with a folder component puts the note in the notebook named by its first segment
6//! (found by case-insensitive name, else created). A path without one is unfiled.
7
8use std::collections::HashMap;
9use std::path::Path;
10use std::sync::Arc;
11
12use serde::Deserialize;
13use topcoat::{
14 Result,
15 context::{Cx, app_context},
16 router::{content::Form, error::bad_request, page, route},
17 view::{Unescaped, View, view},
18};
19
20use crate::app::export_all::sanitize;
21use crate::components::button::{ButtonSize, ButtonVariant, button_variants};
22use crate::export;
23use crate::i18n::{self, Msg, t};
24use crate::hub::Hub;
25use crate::import::{heading_title, markdown_to_doc, rewrite_media, starts_with_heading};
26use crate::store::Store;
27
28/// Files at least this big are stored as markdown first, then get their doc built
29/// (in the background when another import is building one).
30const BUILD_LATER_BYTES: usize = 1 << 20;
31
32#[derive(Deserialize)]
33struct ImportForm {
34 /// Path of the file within the chosen folder, or just the file name.
35 path: String,
36 /// The file's contents.
37 text: String,
38 /// JSON object from a file path within the root to its `/media/` URL. Empty for none.
39 #[serde(default)]
40 media: String,
41}
42
43/// POST /import/file: creates a note from one markdown file and answers with its id.
44#[route(POST "/import/file")]
45pub async fn import_file(cx: &Cx, Form(input): Form<ImportForm>) -> Result<String> {
46 let store = app_context::<Arc<Store>>(cx);
47
48 let path = input.path.replace('\\', "/");
49 let segments: Vec<&str> = path
50 .split('/')
51 .map(str::trim)
52 .filter(|s| !s.is_empty() && *s != "." && *s != "..")
53 .collect();
54 let Some(file_name) = segments.last().copied() else {
55 return Err(bad_request("missing file name").into());
56 };
57 let file = Path::new(file_name);
58 let is_markdown = file
59 .extension()
60 .and_then(|e| e.to_str())
61 .is_some_and(|e| matches!(e.to_ascii_lowercase().as_str(), "md" | "markdown" | "txt"));
62 if !is_markdown {
63 return Err(bad_request("only .md, .markdown and .txt files can be imported").into());
64 }
65 let stem = file
66 .file_stem()
67 .and_then(|s| s.to_str())
68 .unwrap_or(file_name)
69 .to_owned();
70
71 // The first folder below the selected root is the notebook. Files directly in the
72 // root are unfiled.
73 let notebook = (segments.len() >= 2).then(|| sanitize(segments[0]));
74
75 // A note's title is its first block's text. Without a leading heading, the file
76 // name becomes one, so the note is listed under the file's name.
77 // Front matter goes first, or it would no longer lead the file once a heading is
78 // put in front of it.
79 let media: HashMap<String, String> = if input.media.is_empty() {
80 HashMap::new()
81 } else {
82 match serde_json::from_str(&input.media) {
83 Ok(map) => map,
84 Err(_) => return Err(bad_request("malformed media map").into()),
85 }
86 };
87 let text = crate::import::strip_front_matter(&input.text).to_owned();
88 let text = rewrite_media(&text, &segments.join("/"), &media);
89 if text.len() >= BUILD_LATER_BYTES {
90 let markdown = tokio::task::spawn_blocking(move || {
91 let markdown = if starts_with_heading(&text) { text } else { format!("# {stem}\n\n{text}") };
92 let title = heading_title(&markdown);
93 (markdown, title)
94 });
95 let (markdown, title) = markdown.await.map_err(|e| topcoat::Error::from_anyhow(e.into()))?;
96 let id = store
97 .import_note(notebook.as_deref(), None, &title, &markdown, &[], None)
98 .await
99 .map_err(topcoat::Error::from_anyhow)?;
100 app_context::<Arc<Hub>>(cx).build_now(store, &id).await;
101 return Ok(id);
102 }
103 // Parsing a big file takes a while: off the async workers.
104 let (snapshot, title, body, links, export) = tokio::task::spawn_blocking(move || -> anyhow::Result<_> {
105 let doc = if starts_with_heading(&text) {
106 markdown_to_doc(&text)?
107 } else {
108 markdown_to_doc(&format!("# {stem}\n\n{text}"))?
109 };
110 // Stored as a snapshot, which the note's room loads lazily on first open.
111 let snapshot = doc.export(loro::ExportMode::Snapshot)?;
112 let body = export::Body::read(&doc);
113 let links = body.note_links();
114 // A note with note links exports through its cached export markdown, rendered
115 // here once rather than by the first export of every note.
116 let export = if links.is_empty() { None } else { body.markdown_deferred() };
117 Ok((snapshot, body.title(), body.markdown(), links, export))
118 })
119 .await
120 .map_err(|e| topcoat::Error::from_anyhow(e.into()))?
121 .map_err(topcoat::Error::from_anyhow)?;
122
123 store
124 .import_note(notebook.as_deref(), Some(&snapshot), &title, &body, &links, export.as_deref())
125 .await
126 .map_err(topcoat::Error::from_anyhow)
127}
128
129/// GET /import: picks markdown files or a folder and imports them one by one.
130#[page]
131async fn import_page(cx: &Cx) -> Result<impl View> {
132 let lang = i18n::lang(cx);
133 let title = t(lang, Msg::Import);
134 let help = t(lang, Msg::ImportHelp);
135 let choose_files = t(lang, Msg::ChooseFiles);
136 let choose_folder = t(lang, Msg::ChooseFolder);
137 let progress = t(lang, Msg::ImportProgress);
138 let done_one = t(lang, Msg::ImportDoneOne);
139 let done_other = t(lang, Msg::ImportDoneMany);
140 let failed = t(lang, Msg::ImportFailed);
141 let none = t(lang, Msg::ImportNoFiles);
142 let go_to_notes = t(lang, Msg::ImportGoToNotes);
143
144 Ok(view! {
145 <div class="mx-auto flex w-full max-w-3xl flex-col">
146 <header class="sticky top-0 z-10 flex flex-wrap items-start justify-between gap-4 border-b border-border bg-background px-4 py-5 lg:px-8">
147 <div class="min-w-0">
148 <h1 class="text-xl font-semibold tracking-tight">(title)</h1>
149 <p class="mt-1 text-sm text-muted-foreground">(help)</p>
150 </div>
151 </header>
152 <div
153 id="import"
154 class="flex flex-col gap-4 px-4 py-6 lg:px-8"
155 data-progress=(progress)
156 data-done-one=(done_one)
157 data-done-other=(done_other)
158 data-failed=(failed)
159 data-none=(none)
160 >
161 <div class="flex flex-wrap gap-3">
162 <label class="relative inline-flex rounded-control has-focus-visible:outline-2 has-focus-visible:outline-offset-2 has-focus-visible:outline-ring">
163 <input id="import-files" type="file" multiple=(true) class="sr-only">
164 <span class=(button_variants(ButtonVariant::Outline, ButtonSize::Md))>(choose_files)</span>
165 </label>
166 <label class="relative inline-flex rounded-control has-focus-visible:outline-2 has-focus-visible:outline-offset-2 has-focus-visible:outline-ring">
167 <input id="import-folder" type="file" webkitdirectory=(true) class="sr-only">
168 <span class=(button_variants(ButtonVariant::Outline, ButtonSize::Md))>(choose_folder)</span>
169 </label>
170 </div>
171 <p id="import-status" aria-live="polite" class="font-mono text-xs tabular-nums text-muted-foreground"></p>
172 <p id="import-link" class="hidden">
173 <a href="/" class="text-sm font-medium underline underline-offset-4">(go_to_notes)</a>
174 </p>
175 </div>
176 </div>
177 <script>(Unescaped::new_unchecked(IMPORT_SCRIPT))</script>
178 })
179}
180
181/// Collects the chosen files, keeps markdown and text as notes and everything else as
182/// media, and posts the notes one at a time so that a notebook created by one file is
183/// found by the next. Each note's media references are uploaded first, once per file.
184/// A selection of media alone becomes one note per media file. The status line and the
185/// done text come from the data attributes on #import, so the script has no strings.
186pub const IMPORT_SCRIPT: &str = r#"
187(function () {
188 var root = document.getElementById('import');
189 if (!root) return;
190 var status = document.getElementById('import-status');
191 var link = document.getElementById('import-link');
192 var files = document.getElementById('import-files');
193 var folder = document.getElementById('import-folder');
194 var supported = /\.(md|markdown|txt)$/i;
195 var embedded = /\.(png|jpg|jpeg|gif|webp|avif|bmp|mp3|m4a|wav|flac|aac|ogg|oga|opus|weba|mp4|m4v|webm|mov|ogv)$/i;
196 var busy = false;
197
198 function fill(template, values) {
199 return Object.keys(values).reduce(function (text, key) {
200 return text.split('{' + key + '}').join(String(values[key]));
201 }, template);
202 }
203
204 function baseName(path) {
205 return path.slice(path.lastIndexOf('/') + 1);
206 }
207
208 function stemOf(name) {
209 var dot = name.lastIndexOf('.');
210 return dot > 0 ? name.slice(0, dot) : name;
211 }
212
213 // Dotfiles and files inside dot-folders (such as .obsidian) are not imported.
214 function hidden(path) {
215 return path.split('/').some(function (part) { return part.charAt(0) === '.'; });
216 }
217
218 // Whether the note text names the file, raw or percent-encoded. `lower` is lowercased.
219 function mentions(lower, name) {
220 return lower.indexOf(name.toLowerCase()) >= 0 ||
221 lower.indexOf(encodeURI(name).toLowerCase()) >= 0;
222 }
223
224 // The note text that embeds a media file on its own.
225 function ownText(item) {
226 var dest = /\s/.test(item.name) ? '<' + item.name + '>' : item.name;
227 if (embedded.test(item.name)) return '![' + stemOf(item.name) + '](' + dest + ')';
228 return '[' + item.name + '](' + dest + ')';
229 }
230
231 function upload(item) {
232 return fetch('/media?name=' + encodeURIComponent(item.file.name), {
233 method: 'POST',
234 body: item.file,
235 credentials: 'same-origin'
236 }).then(function (res) {
237 if (!res.ok) throw new Error('upload');
238 return res.text();
239 });
240 }
241
242 function run(notes, media) {
243 var total = notes.length;
244 var imported = 0;
245 var failed = 0;
246 var index = 0;
247 var uploads = {};
248 busy = true;
249 link.classList.add('hidden');
250
251 function finish() {
252 var text = fill(imported === 1 ? root.dataset.doneOne : root.dataset.doneOther, { n: imported });
253 if (failed > 0) text += ' ' + fill(root.dataset.failed, { m: failed });
254 status.textContent = text;
255 link.classList.remove('hidden');
256 busy = false;
257 }
258
259 // Each media file is uploaded once per run. A failure is counted once and its
260 // reference is left out of every note.
261 function uploadOnce(item) {
262 if (!uploads[item.path]) {
263 uploads[item.path] = upload(item).catch(function () {
264 failed++;
265 return '';
266 });
267 }
268 return uploads[item.path];
269 }
270
271 function next() {
272 if (index >= total) return finish();
273 status.textContent = fill(root.dataset.progress, { done: index + 1, total: total });
274 var note = notes[index++];
275 note.file.text()
276 .then(function (text) {
277 var lower = text.toLowerCase();
278 var refs = media.filter(function (item) { return mentions(lower, item.name); });
279 var map = {};
280 return refs.reduce(function (chain, item) {
281 return chain.then(function () {
282 return uploadOnce(item).then(function (url) {
283 if (url) map[item.path] = url;
284 });
285 });
286 }, Promise.resolve()).then(function () {
287 var body = new URLSearchParams();
288 body.set('path', note.path);
289 body.set('text', text);
290 body.set('media', JSON.stringify(map));
291 return fetch('/import/file', {
292 method: 'POST',
293 headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
294 body: body,
295 credentials: 'same-origin'
296 });
297 });
298 })
299 .then(function (res) {
300 if (res.ok) imported++; else failed++;
301 })
302 .catch(function () { failed++; })
303 .then(next);
304 }
305
306 next();
307 }
308
309 function onChange(input, fromFolder) {
310 input.addEventListener('change', function () {
311 if (busy) return;
312 var picked = Array.prototype.slice.call(input.files || []);
313 input.value = '';
314 var notes = [];
315 var media = [];
316 picked.forEach(function (file) {
317 var path = file.name;
318 if (fromFolder) {
319 var rel = file.webkitRelativePath || file.name;
320 var slash = rel.indexOf('/');
321 path = slash >= 0 ? rel.slice(slash + 1) : rel;
322 }
323 if (hidden(path)) return;
324 if (supported.test(file.name)) {
325 notes.push({ file: file, path: path });
326 } else {
327 media.push({ file: file, path: path, name: baseName(path) });
328 }
329 });
330 if (notes.length === 0) {
331 notes = media.map(function (item) {
332 return {
333 file: new Blob([ownText(item)]),
334 path: item.path.replace(/(\.[^.\/]*)?$/, '.md')
335 };
336 });
337 }
338 if (notes.length === 0) {
339 status.textContent = root.dataset.none;
340 link.classList.add('hidden');
341 return;
342 }
343 run(notes, media);
344 });
345 }
346
347 onChange(files, false);
348 onChange(folder, true);
349})();
350"#;