//! Markdown import: POST /import/file creates one note from one file, and GET /import is //! the page that picks files or a folder and sends them one at a time. //! //! The browser sends each path with the selected root folder already stripped. A path //! with a folder component puts the note in the notebook named by its first segment //! (found by case-insensitive name, else created). A path without one is unfiled. use std::collections::HashMap; use std::path::Path; use std::sync::Arc; use serde::Deserialize; use topcoat::{ Result, context::{Cx, app_context}, router::{content::Form, error::bad_request, page, route}, view::{Unescaped, View, view}, }; use crate::app::export_all::sanitize; use crate::components::button::{ButtonSize, ButtonVariant, button_variants}; use crate::export; use crate::i18n::{self, Msg, t}; use crate::hub::Hub; use crate::import::{heading_title, markdown_to_doc, rewrite_media, starts_with_heading}; use crate::store::Store; /// Files at least this big are stored as markdown first, then get their doc built /// (in the background when another import is building one). const BUILD_LATER_BYTES: usize = 1 << 20; #[derive(Deserialize)] struct ImportForm { /// Path of the file within the chosen folder, or just the file name. path: String, /// The file's contents. text: String, /// JSON object from a file path within the root to its `/media/` URL. Empty for none. #[serde(default)] media: String, } /// POST /import/file: creates a note from one markdown file and answers with its id. #[route(POST "/import/file")] pub async fn import_file(cx: &Cx, Form(input): Form) -> Result { let store = app_context::>(cx); let path = input.path.replace('\\', "/"); let segments: Vec<&str> = path .split('/') .map(str::trim) .filter(|s| !s.is_empty() && *s != "." && *s != "..") .collect(); let Some(file_name) = segments.last().copied() else { return Err(bad_request("missing file name").into()); }; let file = Path::new(file_name); let is_markdown = file .extension() .and_then(|e| e.to_str()) .is_some_and(|e| matches!(e.to_ascii_lowercase().as_str(), "md" | "markdown" | "txt")); if !is_markdown { return Err(bad_request("only .md, .markdown and .txt files can be imported").into()); } let stem = file .file_stem() .and_then(|s| s.to_str()) .unwrap_or(file_name) .to_owned(); // The first folder below the selected root is the notebook. Files directly in the // root are unfiled. let notebook = (segments.len() >= 2).then(|| sanitize(segments[0])); // A note's title is its first block's text. Without a leading heading, the file // name becomes one, so the note is listed under the file's name. // Front matter goes first, or it would no longer lead the file once a heading is // put in front of it. let media: HashMap = if input.media.is_empty() { HashMap::new() } else { match serde_json::from_str(&input.media) { Ok(map) => map, Err(_) => return Err(bad_request("malformed media map").into()), } }; let text = crate::import::strip_front_matter(&input.text).to_owned(); let text = rewrite_media(&text, &segments.join("/"), &media); if text.len() >= BUILD_LATER_BYTES { let markdown = tokio::task::spawn_blocking(move || { let markdown = if starts_with_heading(&text) { text } else { format!("# {stem}\n\n{text}") }; let title = heading_title(&markdown); (markdown, title) }); let (markdown, title) = markdown.await.map_err(|e| topcoat::Error::from_anyhow(e.into()))?; let id = store .import_note(notebook.as_deref(), None, &title, &markdown, &[], None) .await .map_err(topcoat::Error::from_anyhow)?; app_context::>(cx).build_now(store, &id).await; return Ok(id); } // Parsing a big file takes a while: off the async workers. let (snapshot, title, body, links, export) = tokio::task::spawn_blocking(move || -> anyhow::Result<_> { let doc = if starts_with_heading(&text) { markdown_to_doc(&text)? } else { markdown_to_doc(&format!("# {stem}\n\n{text}"))? }; // Stored as a snapshot, which the note's room loads lazily on first open. let snapshot = doc.export(loro::ExportMode::Snapshot)?; let body = export::Body::read(&doc); let links = body.note_links(); // A note with note links exports through its cached export markdown, rendered // here once rather than by the first export of every note. let export = if links.is_empty() { None } else { body.markdown_deferred() }; Ok((snapshot, body.title(), body.markdown(), links, export)) }) .await .map_err(|e| topcoat::Error::from_anyhow(e.into()))? .map_err(topcoat::Error::from_anyhow)?; store .import_note(notebook.as_deref(), Some(&snapshot), &title, &body, &links, export.as_deref()) .await .map_err(topcoat::Error::from_anyhow) } /// GET /import: picks markdown files or a folder and imports them one by one. #[page] async fn import_page(cx: &Cx) -> Result { let lang = i18n::lang(cx); let title = t(lang, Msg::Import); let help = t(lang, Msg::ImportHelp); let choose_files = t(lang, Msg::ChooseFiles); let choose_folder = t(lang, Msg::ChooseFolder); let progress = t(lang, Msg::ImportProgress); let done_one = t(lang, Msg::ImportDoneOne); let done_other = t(lang, Msg::ImportDoneMany); let failed = t(lang, Msg::ImportFailed); let none = t(lang, Msg::ImportNoFiles); let go_to_notes = t(lang, Msg::ImportGoToNotes); Ok(view! {

(title)

(help)

}) } /// Collects the chosen files, keeps markdown and text as notes and everything else as /// media, and posts the notes one at a time so that a notebook created by one file is /// found by the next. Each note's media references are uploaded first, once per file. /// A selection of media alone becomes one note per media file. The status line and the /// done text come from the data attributes on #import, so the script has no strings. pub const IMPORT_SCRIPT: &str = r#" (function () { var root = document.getElementById('import'); if (!root) return; var status = document.getElementById('import-status'); var link = document.getElementById('import-link'); var files = document.getElementById('import-files'); var folder = document.getElementById('import-folder'); var supported = /\.(md|markdown|txt)$/i; var embedded = /\.(png|jpg|jpeg|gif|webp|avif|bmp|mp3|m4a|wav|flac|aac|ogg|oga|opus|weba|mp4|m4v|webm|mov|ogv)$/i; var busy = false; function fill(template, values) { return Object.keys(values).reduce(function (text, key) { return text.split('{' + key + '}').join(String(values[key])); }, template); } function baseName(path) { return path.slice(path.lastIndexOf('/') + 1); } function stemOf(name) { var dot = name.lastIndexOf('.'); return dot > 0 ? name.slice(0, dot) : name; } // Dotfiles and files inside dot-folders (such as .obsidian) are not imported. function hidden(path) { return path.split('/').some(function (part) { return part.charAt(0) === '.'; }); } // Whether the note text names the file, raw or percent-encoded. `lower` is lowercased. function mentions(lower, name) { return lower.indexOf(name.toLowerCase()) >= 0 || lower.indexOf(encodeURI(name).toLowerCase()) >= 0; } // The note text that embeds a media file on its own. function ownText(item) { var dest = /\s/.test(item.name) ? '<' + item.name + '>' : item.name; if (embedded.test(item.name)) return '![' + stemOf(item.name) + '](' + dest + ')'; return '[' + item.name + '](' + dest + ')'; } function upload(item) { return fetch('/media?name=' + encodeURIComponent(item.file.name), { method: 'POST', body: item.file, credentials: 'same-origin' }).then(function (res) { if (!res.ok) throw new Error('upload'); return res.text(); }); } function run(notes, media) { var total = notes.length; var imported = 0; var failed = 0; var index = 0; var uploads = {}; busy = true; link.classList.add('hidden'); function finish() { var text = fill(imported === 1 ? root.dataset.doneOne : root.dataset.doneOther, { n: imported }); if (failed > 0) text += ' ' + fill(root.dataset.failed, { m: failed }); status.textContent = text; link.classList.remove('hidden'); busy = false; } // Each media file is uploaded once per run. A failure is counted once and its // reference is left out of every note. function uploadOnce(item) { if (!uploads[item.path]) { uploads[item.path] = upload(item).catch(function () { failed++; return ''; }); } return uploads[item.path]; } function next() { if (index >= total) return finish(); status.textContent = fill(root.dataset.progress, { done: index + 1, total: total }); var note = notes[index++]; note.file.text() .then(function (text) { var lower = text.toLowerCase(); var refs = media.filter(function (item) { return mentions(lower, item.name); }); var map = {}; return refs.reduce(function (chain, item) { return chain.then(function () { return uploadOnce(item).then(function (url) { if (url) map[item.path] = url; }); }); }, Promise.resolve()).then(function () { var body = new URLSearchParams(); body.set('path', note.path); body.set('text', text); body.set('media', JSON.stringify(map)); return fetch('/import/file', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: body, credentials: 'same-origin' }); }); }) .then(function (res) { if (res.ok) imported++; else failed++; }) .catch(function () { failed++; }) .then(next); } next(); } function onChange(input, fromFolder) { input.addEventListener('change', function () { if (busy) return; var picked = Array.prototype.slice.call(input.files || []); input.value = ''; var notes = []; var media = []; picked.forEach(function (file) { var path = file.name; if (fromFolder) { var rel = file.webkitRelativePath || file.name; var slash = rel.indexOf('/'); path = slash >= 0 ? rel.slice(slash + 1) : rel; } if (hidden(path)) return; if (supported.test(file.name)) { notes.push({ file: file, path: path }); } else { media.push({ file: file, path: path, name: baseName(path) }); } }); if (notes.length === 0) { notes = media.map(function (item) { return { file: new Blob([ownText(item)]), path: item.path.replace(/(\.[^.\/]*)?$/, '.md') }; }); } if (notes.length === 0) { status.textContent = root.dataset.none; link.classList.add('hidden'); return; } run(notes, media); }); } onChange(files, false); onChange(folder, true); })(); "#;