{ "always_run_in_app": false, "icon": { "color": "deep-blue", "glyph": "sf:brain.head.profile" }, "name": "Archive to Obsidian", "script": "// Variables used by Scriptable.\n// These must be at the very top of the file. Do not edit.\n// icon-color: deep-blue; icon-glyph: sf:brain.head.profile;\n// share-sheet-inputs: plain-text, image, url, file-url;\n\n/**\n * Archive in Obsidian\n *\n * Archive files, images, URLs and text directly\n * from the iOS Share Sheet into an Obsidian vault.\n */\n\nconst CONFIG = {\n bookmark: \"ObsidianVault\",\n notesFolder: \"Document Archive\",\n attachmentsFolder: \"Attachments\",\n embedAttachments: true,\n notifyOnSuccess: true,\n openNoteShortcut: \"Open Obsidian Note\",\n notificationDelay: 0, // Seconds; 0 for immediate delivery.\n debug: false,\n};\n\nconst fm = FileManager.local();\nlet stage = \"Initialization\";\n\n// --- Utility functions ---\n\nasync function notify(title, body, openURL = null, delay = 0) {\n const notification = new Notification();\n notification.title = title;\n notification.body = String(body);\n if (openURL) notification.openURL = openURL;\n if (delay > 0) {\n notification.setTriggerDate(new Date(Date.now() + delay * 1000));\n }\n await notification.schedule();\n}\n\nasync function debug(message) {\n stage = message;\n console.log(message);\n\n if (CONFIG.debug) {\n try {\n await notify(\"Archive Debug\", message);\n } catch (e) {\n console.log(\"Notification failed: \" + e);\n }\n }\n}\n\nfunction timestamp(date = new Date()) {\n const pad = n => String(n).padStart(2, \"0\");\n return (\n `${date.getFullYear()}-` +\n `${pad(date.getMonth() + 1)}-` +\n `${pad(date.getDate())}T` +\n `${pad(date.getHours())}:` +\n `${pad(date.getMinutes())}:` +\n `${pad(date.getSeconds())}`\n );\n}\n\nfunction sanitize(name) {\n return name\n .replace(/[\\\\/:*?\"<>|#^\\[\\]\\x00-\\x1f]/g, \"-\")\n .replace(/\\s+/g, \" \")\n .replace(/^[.]+|[. ]+$/g, \"\")\n .trim() || \"Untitled\";\n}\n\nfunction splitFilename(name) {\n const dot = name.lastIndexOf(\".\");\n return dot > 0\n ? [name.slice(0, dot), name.slice(dot)]\n : [name, \"\"];\n}\n\nfunction uniquePath(folder, filename) {\n const [base, ext] = splitFilename(filename);\n let path = fm.joinPath(folder, filename);\n let n = 2;\n\n while (fm.fileExists(path)) {\n path = fm.joinPath(\n folder, `${base} (${n++})${ext}`\n );\n }\n\n return path;\n}\n\nfunction ensureFolder(path) {\n if (!fm.fileExists(path)) {\n fm.createDirectory(path, true);\n }\n}\n\nfunction encodePath(path) {\n return path.split(\"/\")\n .map(encodeURIComponent)\n .join(\"/\")\n .replace(/\\(/g, \"%28\")\n .replace(/\\)/g, \"%29\");\n}\n\nfunction attachmentLink(filename) {\n const embeddable =\n /\\.(pdf|png|jpe?g|gif|webp|svg|bmp|avif|mp3|wav|m4a|mp4|webm|mov|ogg|flac)$/i\n .test(filename);\n\n const prefix =\n CONFIG.embedAttachments && embeddable\n ? \"!\" : \"\";\n\n const path = encodePath(\n `../${CONFIG.attachmentsFolder}/${filename}`\n );\n\n const label = filename.replace(/[\\[\\]]/g, \"\");\n\n return `${prefix}[${label}](${path})`;\n}\n\nasync function promptTitle(defaultTitle) {\n await debug(\"5a. Creating title alert\");\n\n const alert = new Alert();\n alert.title = \"Archive in Obsidian\";\n alert.message = \"Enter a title for the note.\";\n alert.addTextField(\"Title\", defaultTitle);\n alert.addAction(\"Archive\");\n alert.addCancelAction(\"Cancel\");\n\n await debug(\"5b. Presenting title alert\");\n\n const result = await alert.presentAlert();\n\n await debug(\"5c. Alert returned: \" + result);\n\n if (result === -1) {\n return null;\n }\n\n return sanitize(alert.textFieldValue(0));\n}\n\n// --- Main ---\n\nasync function main() {\n await debug(\"1. Main started\");\n\n await debug(\n \"1a. Execution context\\n\" +\n `In app: ${config.runsInApp}\\n` +\n `In extension: ${config.runsInActionExtension}`\n );\n\n if (!fm.bookmarkExists(CONFIG.bookmark)) {\n throw new Error(\n `Missing file bookmark: ${CONFIG.bookmark}`\n );\n }\n\n await debug(\"2. Bookmark exists\");\n\n const vault = fm.bookmarkedPath(CONFIG.bookmark);\n\n await debug(\"3. Vault resolved:\\n\" + vault);\n\n const notesDir = fm.joinPath(\n vault, CONFIG.notesFolder\n );\n\n const attachmentsDir = fm.joinPath(\n vault, CONFIG.attachmentsFolder\n );\n\n const files = args.fileURLs || [];\n const urls = args.urls || [];\n const texts = args.plainTexts || [];\n\n // Avoid saving images twice when iOS supplies\n // both a file URL and an image representation.\n const images = files.length\n ? [] : (args.images || []);\n\n await debug(\n `4. Inputs received:\\n` +\n `Files: ${files.length}\\n` +\n `Images: ${images.length}\\n` +\n `URLs: ${urls.length}\\n` +\n `Texts: ${texts.length}`\n );\n\n if (\n !files.length && !images.length &&\n !urls.length && !texts.length\n ) {\n throw new Error(\n \"No content received. Run this script \" +\n \"from the iOS Share Sheet.\"\n );\n }\n\n const now = timestamp();\n const date = now.slice(0, 10);\n\n // Suggest a title based on shared content.\n let defaultTitle = \"Untitled\";\n\n if (files.length) {\n await debug(\n \"4a. First shared file:\\n\" + files[0]\n );\n\n const filename = fm.fileName(files[0], true);\n\n await debug(\n \"4b. Extracted filename: \" + filename\n );\n\n defaultTitle = splitFilename(filename)[0];\n\n } else if (images.length) {\n defaultTitle = \"Image\";\n\n } else if (urls.length) {\n defaultTitle = urls[0]\n .replace(/^https?:\\/\\//, \"\")\n .split(\"/\")[0];\n\n } else if (texts.length) {\n defaultTitle = texts[0]\n .split(\"\\n\")[0]\n .slice(0, 80);\n }\n\n await debug(\"5. Default title: \" + defaultTitle);\n\n const title = await promptTitle(defaultTitle);\n\n await debug(\"6. Title received: \" + title);\n\n if (title === null) {\n await debug(\"6a. Cancelled by user\");\n return;\n }\n\n await debug(\"6b. Ensuring notes directory\");\n\n ensureFolder(notesDir);\n\n await debug(\"6c. Ensuring attachments directory\");\n\n ensureFolder(attachmentsDir);\n\n const notePath = uniquePath(\n notesDir, `${date} ${title}.md`\n );\n\n const noteName = fm.fileName(notePath, false);\n\n await debug(\"6d. Note path:\\n\" + notePath);\n\n const createdFiles = [];\n const links = [];\n\n try {\n // Preserve shared files in original format.\n for (const source of files) {\n await debug(\n \"7a. Processing source:\\n\" + source\n );\n\n const original = fm.fileName(source, true);\n\n await debug(\n \"7b. Original filename: \" + original\n );\n\n const destination = uniquePath(\n attachmentsDir,\n `${noteName} - ${sanitize(original)}`\n );\n\n await debug(\n \"7c. Source exists: \" +\n fm.fileExists(source)\n );\n\n await debug(\n \"7d. Copying file to:\\n\" + destination\n );\n\n fm.copy(source, destination);\n createdFiles.push(destination);\n\n await debug(\"7e. File copied successfully\");\n\n links.push(\n attachmentLink(\n fm.fileName(destination, true)\n )\n );\n\n await debug(\"7f. Attachment link generated\");\n }\n\n // Handle images shared without a file URL.\n for (let i = 0; i < images.length; i++) {\n const destination = uniquePath(\n attachmentsDir,\n `${noteName} - Image ${i + 1}.png`\n );\n\n await debug(\n \"7g. Writing image to:\\n\" + destination\n );\n\n fm.writeImage(destination, images[i]);\n createdFiles.push(destination);\n\n await debug(\"7h. Image written successfully\");\n\n links.push(\n attachmentLink(\n fm.fileName(destination, true)\n )\n );\n }\n\n // Build Markdown note.\n await debug(\"8. Building Markdown note\");\n\n const sections = [\n \"---\",\n `Created: ${now}`,\n `Updated: ${now}`,\n \"---\",\n \"\",\n ];\n\n if (urls.length) {\n sections.push(\n ...urls.map(url => `<${url}>`), \"\"\n );\n }\n\n if (texts.length) {\n sections.push(texts.join(\"\\n\\n\"), \"\");\n }\n\n if (links.length) {\n sections.push(links.join(\"\\n\\n\"), \"\");\n }\n\n await debug(\n \"8a. Writing note:\\n\" + notePath\n );\n\n fm.writeString(notePath, sections.join(\"\\n\"));\n\n await debug(\"8b. Note written successfully\");\n\n } catch (error) {\n // Roll back copied attachments on failure.\n console.error(\"Rolling back attachments\");\n\n for (const path of createdFiles) {\n try {\n fm.remove(path);\n } catch (cleanupError) {\n console.error(String(cleanupError));\n }\n }\n\n throw error;\n }\n\n if (CONFIG.notifyOnSuccess) {\n try {\n const vaultName = fm.fileName(vault, true);\n const relativePath = notePath.slice(vault.length + 1);\n const obsidianURL = \"obsidian://open?vault=\" +\n encodeURIComponent(vaultName) + \"&file=\" +\n encodeURIComponent(relativePath);\n // Wake Obsidian before resolving the note in its file index.\n const launcherURL = CONFIG.openNoteShortcut\n ? \"shortcuts://run-shortcut?name=\" +\n encodeURIComponent(CONFIG.openNoteShortcut) +\n \"&input=text&text=\" + encodeURIComponent(obsidianURL)\n : obsidianURL;\n await notify(\n \"Archived in Obsidian\", noteName, launcherURL,\n CONFIG.notificationDelay\n );\n } catch (error) {\n console.log(String(error));\n }\n }\n}\n\n// --- Entry point ---\n\ntry {\n await debug(\"0. Script entered\");\n await main();\n await debug(\"9. Main completed\");\n\n} catch (error) {\n const message =\n `Failed at: ${stage}\\n\\n` +\n String(error) + \"\\n\\n\" +\n (error.stack || \"\");\n\n console.error(message);\n\n await notify(\"Archive FAILED\", message);\n}\n\nScript.complete();\n", "share_sheet_inputs": [ "plain-text", "image", "url", "file-url" ] }