WritingSpace/.obsidian/plugins/local-any-files/main.js
2025-01-22 09:00:25 +01:00

14 lines
No EOL
28 KiB
JavaScript

/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/
var B=Object.defineProperty;var U=Object.getOwnPropertyDescriptor;var q=Object.getOwnPropertyNames;var Z=Object.prototype.hasOwnProperty;var G=(d,e)=>{for(var t in e)B(d,t,{get:e[t],enumerable:!0})},X=(d,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of q(e))!Z.call(d,i)&&i!==t&&B(d,i,{get:()=>e[i],enumerable:!(s=U(e,i))||s.enumerable});return d};var K=d=>X(B({},"__esModule",{value:!0}),d);var J={};G(J,{default:()=>j});module.exports=K(J);var F=require("obsidian");var w={image:[".png",".jpg",".jpeg",".gif",".bmp",".svg",".webp",".tiff",".ico",".raw",".heic",".heif",".avif",".jfif"],officeFile:[".doc",".docx",".xls",".xlsx",".ppt",".pptx",".pdf",".odt",".ods",".odp",".rtf",".txt",".csv",".epub",".pages",".numbers",".key"],archivePackage:[".zip",".rar",".7z",".tar",".gz",".bz2",".xz",".iso",".tgz",".z",".bzip2",".cab"],music:[".mp3",".wav",".flac",".m4a",".ogg",".aac",".wma",".aiff",".alac",".mid",".midi",".opus",".amr"],video:[".mp4",".avi",".mkv",".mov",".wmv",".flv",".webm",".m4v",".mpg",".mpeg",".3gp",".ogv",".ts",".vob"],code:[".js",".ts",".jsx",".tsx",".html",".css",".scss",".json",".xml",".yaml",".yml",".md",".py",".java",".cpp",".c",".cs",".php",".rb",".go",".rs",".swift"],font:[".ttf",".otf",".woff",".woff2",".eot"],design:[".psd",".ai",".eps",".sketch",".fig",".xd",".blend",".obj",".fbx",".stl",".3ds",".dae"],database:[".sql",".db",".sqlite",".mdb",".accdb",".csv",".tsv"],ebook:[".epub",".mobi",".azw",".azw3",".fb2",".lit",".djvu"],academic:[".bib",".tex",".sty",".cls",".csl",".nb",".mat",".r",".rmd",".ipynb"]},H={tasks:["extract","download","replace"],scope:"currentFile",presetExtensions:["image","officeFile"],customExtensions:[],storePath:"assets/${path}",storeFileName:"${originalName}"};var k=require("obsidian");var u=require("obsidian");var h=class{constructor(e,t,s){this.containerEl=e;this.plugin=t;this.defaultScope=s}display(){let{containerEl:e}=this;e.empty(),new u.Setting(e).setName("Processing").setHeading(),this.addScopeDropdown(),this.addTasksDropdown(),new u.Setting(e).setName("File extensions").setHeading(),this.addPresetExtensions(),this.addCustomExtensions(),new u.Setting(e).setName("Storage").setHeading(),this.addStorePath()}addScopeDropdown(){let e={currentFile:"Current file only",currentFolder:"Current folder",allFiles:"All files in vault"};if(this.defaultScope==="singleItem"){new u.Setting(this.containerEl).setName("Scope").setDesc("Download single item").addDropdown(t=>{t.addOption("singleItem","Single item").setValue("singleItem").onChange(async s=>{this.plugin.settings.scope=s,await this.plugin.saveSettings()})});return}new u.Setting(this.containerEl).setName("Scope").setDesc("Select which files to process").addDropdown(t=>{Object.entries(e).forEach(([s,i])=>{t.addOption(s,i)}),t.setValue((()=>this.plugin.settings.scope==="singleItem"?"currentFile":this.defaultScope||this.plugin.settings.scope)()).onChange(async s=>{this.plugin.settings.scope=s,await this.plugin.saveSettings()})})}addTasksDropdown(){let t=new u.Setting(this.containerEl).setName("Tasks").setDesc("Select which tasks to perform").setClass("tasks-setting").settingEl.createDiv("tasks-container"),s={extract:"Extract links",download:"Download files",replace:"Replace links"},i={};Object.entries(s).forEach(([n,a])=>{new u.Setting(t).setClass("task-item").setName(a).addToggle(o=>{i[n]=o,o.setValue(this.plugin.settings.tasks.includes(n)).onChange(async r=>{if(r)n==="download"?this.plugin.settings.tasks.includes("extract")||(this.plugin.settings.tasks.push("extract"),i.extract.setValue(!0)):n==="replace"&&(this.plugin.settings.tasks.includes("extract")||(this.plugin.settings.tasks.push("extract"),i.extract.setValue(!0)),this.plugin.settings.tasks.includes("download")||(this.plugin.settings.tasks.push("download"),i.download.setValue(!0))),this.plugin.settings.tasks.includes(n)||this.plugin.settings.tasks.push(n);else if(n==="extract"&&(this.plugin.settings.tasks.includes("download")||this.plugin.settings.tasks.includes("replace"))){o.setValue(!0),new u.Notice("Cannot disable Extract links while Download files or Replace links is enabled");return}else if(n==="download"&&this.plugin.settings.tasks.includes("replace")){o.setValue(!0),new u.Notice("Cannot disable Download files while Replace links is enabled");return}else this.plugin.settings.tasks=this.plugin.settings.tasks.filter(l=>l!==n);await this.plugin.saveSettings()})})})}addPresetExtensions(){let t=new u.Setting(this.containerEl).setName("Preset extensions").setDesc("Select preset file types").setClass("presets-setting").settingEl.createDiv("presets-container");Object.entries({image:"Image files",officeFile:"Office documents",archivePackage:"Archive files",music:"Music files",video:"Video files",code:"Code & development",font:"Font files",design:"3D & design files",database:"Database files",ebook:"E-book formats",academic:"Research & academic"}).forEach(([i,n])=>{new u.Setting(t).setClass("preset-item").setName(n).addToggle(a=>{a.setValue(this.plugin.settings.presetExtensions.includes(i)).onChange(async o=>{o&&!this.plugin.settings.presetExtensions.includes(i)?this.plugin.settings.presetExtensions.push(i):o||(this.plugin.settings.presetExtensions=this.plugin.settings.presetExtensions.filter(r=>r!==i)),await this.plugin.saveSettings(),this.addFinalExtensionsDisplay()})})})}addStorePath(){new u.Setting(this.containerEl).setName("Store path").setDesc("Set the path pattern for downloaded files.").addText(e=>{e.setValue(this.plugin.settings.storePath).onChange(async t=>{this.plugin.settings.storePath=t,await this.plugin.saveSettings()})}),new u.Setting(this.containerEl).setName("Store file name").setDesc("Set the file name pattern for downloaded files. The store name has no need to include the file extension").addText(e=>{e.setValue(this.plugin.settings.storeFileName).onChange(async t=>{this.plugin.settings.storeFileName=t,await this.plugin.saveSettings()})})}addCustomExtensions(){let t=new u.Setting(this.containerEl).setName("Custom extensions").setDesc("Add custom file extensions (format: .ext). Use | to add multiple extensions at once (e.g., .pdf|.txt|.md)").setClass("custom-extensions-setting").settingEl.createDiv("custom-extensions-container");t.addClass("vertical-layout");let s=t.createDiv("custom-input-container"),i=s.createEl("input",{type:"text",placeholder:".pdf|.txt|.md"}),n=s.createEl("button",{text:"Add",cls:"mod-cta"}),a=t.createDiv("custom-extensions-tags"),o=()=>{a.empty(),this.plugin.settings.customExtensions.forEach(l=>{let c=a.createDiv("extension-tag custom-extension-tag");c.setText(l);let p=c.createSpan("extension-tag-remove");p.setText("\xD7"),p.addEventListener("click",async()=>{this.plugin.settings.customExtensions=this.plugin.settings.customExtensions.filter(g=>g!==l),await this.plugin.saveSettings(),o(),this.addFinalExtensionsDisplay()})})};o();let r=async()=>{let l=i.value.trim();if(!l)return;let c=l.split("|").map(g=>g.trim().toLowerCase()).filter(g=>g),p=!1;for(let g of c)this.isValidExtension(g)&&!this.plugin.settings.customExtensions.includes(g)&&(this.plugin.settings.customExtensions.push(g),p=!0);p&&(await this.plugin.saveSettings(),i.value="",o(),this.addFinalExtensionsDisplay())};n.addEventListener("click",r),i.addEventListener("keypress",l=>{l.key==="Enter"&&r()})}addFinalExtensionsDisplay(){this.containerEl.querySelectorAll(".extensions-preview-setting").forEach(o=>o.remove());let t=this.containerEl.querySelector(".custom-extensions-setting");if(!t){console.warn("Custom extensions section not found");return}let s=new u.Setting(this.containerEl).setName("Active extensions").setDesc("File extensions that will be processed").setClass("extensions-preview-setting");t.after(s.settingEl);let i=s.settingEl.createDiv("extensions-preview-container");i.addClass("vertical-layout");let n=[...this.plugin.settings.presetExtensions.flatMap(o=>w[o]||[]),...this.plugin.settings.customExtensions.map(o=>o.toLowerCase())].sort((o,r)=>o.localeCompare(r));if(n.length>0){let o=i.createDiv("extensions-box");n.forEach(r=>{o.createDiv("extension-tag").setText(r)})}else i.createDiv("extensions-box").createDiv("extension-empty-text").setText("No extensions selected");let a=document.head.querySelector("style[data-extensions-preview]");a&&a.remove()}getStorageSectionHeaderDesc(){return"Available variables: ${originalName}, ${random}, ${notename}, ${date}, ${time}, ${extension}, ${year} , ${month}, ${day}, ${hour}, ${minute}, ${second}."}static validateSettings(e){let t=[];return e.storePath||t.push("Storage path is required"),e.presetExtensions.length===0&&e.customExtensions.length===0&&t.push("At least one file extension must be selected or added"),{isValid:t.length===0,errors:t}}getFinalProcessingExtensions(){let e=this.plugin.settings.presetExtensions.flatMap(i=>w[i]||[]),t=this.plugin.settings.customExtensions.map(i=>i.toLowerCase()),s=new Set([...e,...t]);return Array.from(s).sort((i,n)=>i.localeCompare(n))}isValidExtension(e){let t=/^\.[a-zA-Z0-9]+[a-zA-Z0-9-]*$/;if(!e)return!1;let s=e.toLowerCase(),i=t.test(s);return i||new u.Notice("Invalid extension format. Extensions must start with a dot followed by letters/numbers (e.g., .pdf)",3e3),i}};var N=class extends k.PluginSettingTab{constructor(t,s){super(t,s);this.plugin=s}display(){let{containerEl:t}=this;t.empty();let s=new h(t,this.plugin);new k.Setting(t).setName("Processing").setHeading(),s.addScopeDropdown(),s.addTasksDropdown(),new k.Setting(t).setName("File extensions").setHeading(),s.addPresetExtensions(),s.addCustomExtensions(),s.addFinalExtensionsDisplay(),new k.Setting(t).setName("Storage").setHeading().setDesc(s.getStorageSectionHeaderDesc()),s.addStorePath()}};var f=require("obsidian");var T=class extends f.Modal{constructor(t,s,i,n){super(t);this.plugin=s;this.documentPath=i;this.onSubmit=n;this.settingsBuilder=new h(this.contentEl,this.plugin,"singleItem"),this.titleEl.setText("Local any files > Download single item")}onOpen(){let{contentEl:t}=this;t.empty(),new f.Setting(t).setName("Processing").setHeading(),this.settingsBuilder.addScopeDropdown(),this.settingsBuilder.addTasksDropdown(),new f.Setting(t).setName("Target Link").setHeading(),t.createEl("div",{cls:"setting-item"}).createEl("div",{cls:"setting-item-description target-link-text",text:this.documentPath}),new f.Setting(t).setName("Storage").setHeading(),this.settingsBuilder.addStorePath(),t.createEl("button",{text:"Start download",cls:"mod-cta"}).addEventListener("click",()=>{this.handleSubmit()})}handleSubmit(){if(!this.plugin.settings.tasks||this.plugin.settings.tasks.length===0){new f.Notice("Please select at least one task.");return}if(!this.plugin.settings.storePath){new f.Notice("Please specify a storage path.");return}this.close(),this.onSubmit()}onClose(){let{contentEl:t}=this;t.empty()}};var V=require("obsidian");var v=require("obsidian");var A=class{static validateSettings(e){let t=[];(!e.tasks||e.tasks.length===0)&&t.push("At least one task must be selected.");let s=this.getAllExtensions(e);s.length===0&&t.push("At least one file extension must be selected or added.");let i=s.filter(n=>!this.isValidExtension(n));return i.length>0&&t.push(`Invalid extension format: ${i.join(", ")}. Extensions must start with a dot and contain only valid characters.`),["currentFile","allFiles","currentFolder"].includes(e.scope)||t.push("Invalid scope selected."),{isValid:t.length===0,errors:t}}static getAllExtensions(e){let t=(e.presetExtensions||[]).flatMap(i=>w[i]||[]),s=e.customExtensions||[];return[...new Set([...t,...s])]}static isValidExtension(e){return/^\.[a-zA-Z0-9]+$/.test(e)}};var $=class extends v.Modal{constructor(t,s,i,n){super(t);this.plugin=s;this.onSubmit=i;this.defaultScope=n;this.settingsBuilder=new h(this.contentEl,this.plugin,this.defaultScope),this.titleEl.setText("Local any files > Options")}onOpen(){let{contentEl:t}=this;t.empty(),new v.Setting(t).setName("Processing").setHeading(),this.settingsBuilder.addScopeDropdown(),this.settingsBuilder.addTasksDropdown(),new v.Setting(t).setName("File extensions").setHeading(),this.settingsBuilder.addPresetExtensions(),this.settingsBuilder.addCustomExtensions(),this.settingsBuilder.addFinalExtensionsDisplay(),new v.Setting(t).setName("Storage").setHeading().setDesc(this.settingsBuilder.getStorageSectionHeaderDesc()),this.settingsBuilder.addStorePath(),t.createEl("button",{text:"Start processing",cls:"mod-cta full-width-button"}).addEventListener("click",()=>{this.handleSubmit()})}async handleSubmit(){let t=A.validateSettings(this.plugin.settings);if(!t.isValid){new v.Notice(`Please fix the following issues:
`+t.errors.join(`
`),5e3);return}this.close(),this.onSubmit()}onClose(){let{contentEl:t}=this;t.empty()}};var _=require("obsidian"),L=class extends _.Modal{constructor(t,s,i){super(t);this.currentLogContainer=null;this.documentStats=new Map;this.progress=0;this.logs=[];this.currentTask=null;this.taskDisplayNames={extract:"Extract links",download:"Download files",replace:"Replace links"};this.stats={totalNotes:0,processedNotes:0,totalLinks:0,downloadedFiles:0,failedFiles:0};this.plugin=s,this.processCallback=i,this.titleEl.setText("Local any files > Processing")}onOpen(){let{contentEl:t}=this;t.empty(),this.statsContainer=t.createDiv({cls:"stats-container"}),this.updateStats();let s=t.createDiv({cls:"custom-progress-section"});this.progressBar=s.createDiv({cls:"custom-progress-bar"}),this.progressFill=this.progressBar.createDiv({cls:"custom-progress-fill"}),this.logsContainer=t.createDiv({cls:"logs-container"}),this.updateProgress(0),this.processCallback()}createCopyableText(t,s,i){let n=s.createSpan({cls:`copyable-text ${i||""}`,text:t});return n.addEventListener("click",async()=>{try{await navigator.clipboard.writeText(t),n.addClass("copied"),setTimeout(()=>n.removeClass("copied"),1e3)}catch(a){console.error("Failed to copy text:",a)}}),n}isTaskEnabled(t){return this.plugin.settings.tasks.includes(t)}updateProgress(t){this.progress=t,this.progressFill&&this.progressFill.style.setProperty("--progress-width",`${t}%`)}updateStats(t){if(t&&(this.stats={...this.stats,...t}),this.statsContainer){this.statsContainer.empty();let s=(i,n,a)=>{let o=this.statsContainer.createDiv({cls:"stat-item"});o.createDiv({cls:`stat-value stat-value-${a}`,text:i.toString()}),o.createDiv({cls:"stat-label",text:n})};s(this.stats.processedNotes,"Notes Processed","processed"),s(this.stats.totalNotes,"Total Notes","total"),s(this.stats.totalLinks,"Links Found","found"),s(this.stats.downloadedFiles,"Downloads","downloads"),s(this.stats.failedFiles,"Failed","failed")}}startDocumentLog(t){let s=this.logsContainer.createDiv({cls:"log-document-container"}),i=s.createDiv({cls:"log-document-header"});i.createDiv({cls:"log-document-title",text:t}),i.createDiv({cls:"log-document-stats"}),this.documentStats.set(t,{links:0,success:0,failed:0}),this.updateDocumentStats(t);let n=s.createDiv({cls:"log-document-content"});return i.addEventListener("click",()=>{i.toggleClass("collapsed",!i.hasClass("collapsed")),n.toggleClass("collapsed",i.hasClass("collapsed"))}),this.currentLogContainer=n,n}updateDocumentStats(t,s){let i=this.documentStats.get(t);if(!i)return;let n=`Links: ${i.links} / Success: ${i.success} / Failed: ${i.failed}`;s&&s.setText(n)}addLog(t,s="info",i){if(i&&!this.isTaskEnabled(i))return;this.logs.push(t);let n=this.currentLogContainer||this.logsContainer,a=n.createDiv({cls:`log log-${s}`});if(t.startsWith("Link: ")){let o=t.substring(6);a.createSpan({text:"Link: "}),this.createCopyableText(o,a,"log-url")}else if(t.startsWith("File: ")){let o=t.substring(6);a.createSpan({text:"File: "}),this.createCopyableText(o,a,"log-url")}else if(t.startsWith("SavedPath: ")){let o=t.substring(t.indexOf(": ")+2);a.createSpan({text:"SavedPath: "}),this.createCopyableText(o.replace("\u2713 ",""),a,"log-saved-path")}else a.setText(t);n.scrollTop=n.scrollHeight}updateDocumentProgress(t,s,i,n){let a=this.documentStats.get(t);a&&(a.links=s,a.success=i,a.failed=n,this.updateDocumentStats(t))}addDivider(t=!1){(this.currentLogContainer||this.logsContainer).createDiv({cls:`log-divider${t?" thick":""}`})}onClose(){let{contentEl:t}=this;t.empty()}};var W=require("obsidian");function I(d){let e=0;for(let t=0;t<d.length;t++){let s=d.charCodeAt(t);e=(e<<5)-e+s,e=e&e}return Math.abs(e).toString(16).substring(0,8)}var D=class{constructor(e,t=[]){this.extensions=e.map(s=>s.toLowerCase()),this.allowImages=t.includes("image")}extractFromText(e){let t=[],s=/!\[([^\]]*)\]\(([^)]+)\)/g,i=/\[([^\]]*)\]\(([^)]+)\)/g,n=/(https?:\/\/[^\s<>)"]+)/g,a=new Set,o=l=>l.startsWith("http://")||l.startsWith("https://"),r;if(this.allowImages)for(;(r=s.exec(e))!==null;){let[l,,c]=r;!a.has(c)&&o(c)&&(a.add(c),t.push({originalLink:c,fileExtension:this.getExtension(c),fileName:this.getFileName(c),position:{start:r.index,end:r.index+l.length},isMarkdownImage:!0}))}for(;(r=i.exec(e))!==null;){let[l,c,p]=r;if(!l.startsWith("!")&&!a.has(p)&&o(p)){a.add(p);let g=this.getExtension(p).toLowerCase();this.extensions.includes(g)&&t.push({originalLink:p,fileExtension:g,fileName:c||this.getFileName(p),position:{start:r.index,end:r.index+l.length},isMarkdownImage:!1})}}for(;(r=n.exec(e))!==null;){let[l]=r;if(!a.has(l)&&o(l)){let c=this.getExtension(l).toLowerCase();this.extensions.includes(c)&&(a.add(l),t.push({originalLink:l,fileExtension:c,fileName:this.getFileName(l),position:{start:r.index,end:r.index+l.length},isMarkdownImage:!1}))}}return t}hasValidExtension(e){let t=e.toLowerCase();return this.extensions.some(s=>t.endsWith(s))}getExtension(e){try{let i=new URL(e).pathname.split("/").pop()||"";i=i.split("?")[0];let n=i.match(/\.([^.]+)$/);return n?"."+n[1].toLowerCase():""}catch(t){let s=e.lastIndexOf(".");return s===-1?"":e.slice(s).toLowerCase()}}getFileName(e){try{let n=(new URL(e).pathname.split("/").pop()||"").split(/[?#]/)[0];if(!n)return"untitled";let a=this.getExtension(e);return n.substring(0,n.length-a.length).replace(/[^a-zA-Z0-9-_]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")+a}catch(t){let s=e.split("/"),i=s[s.length-1]||"untitled",n=this.getExtension(e);return i.substring(0,i.length-n.length).replace(/[^a-zA-Z0-9-_]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")+n}}};var P=class{constructor(e,t,s,i){this.plugin=e,this.storePath=t,this.variables=s,this.storeFileName=i||"${originalName}"}getCleanFileName(e){try{let i=new URL(e).pathname.split("/").pop()||"";return i=i.split("?")[0],i||(i=I(e)),i}catch(t){return I(e)}}getExtension(e){let t=e.lastIndexOf(".");return t===-1?"":e.slice(t).toLowerCase()}getExtensionFromContentType(e){let t={"image/jpeg":".jpeg","image/jpg":".jpg","image/png":".png","image/gif":".gif","image/webp":".webp","image/svg+xml":".svg","image/bmp":".bmp","image/tiff":".tiff","image/vnd.adobe.photoshop":".psd","image/vnd.microsoft.icon":".ico","application/pdf":".pdf","video/mp4":".mp4","video/webm":".webm","audio/mpeg":".mp3","audio/wav":".wav","audio/webm":".weba","application/json":".json","text/json":".json","text/plain":".txt","text/html":".html","text/css":".css","text/javascript":".js","application/javascript":".js","application/xml":".xml","text/xml":".xml","application/zip":".zip","application/x-rar-compressed":".rar","application/x-7z-compressed":".7z","application/x-tar":".tar","application/x-gzip":".gz","application/x-bzip2":".bz2","application/x-xz":".xz","application/x-iso9660-image":".iso","application/x-gzip-compressed":".tgz","application/x-compressed":".z","application/x-bzip2-compressed":".bzip2","application/x-cab-compressed":".cab"},s=e.split(";")[0].trim().toLowerCase();return t[s]||".unknown"}async getLocalPath(e,t,s){let i=this.storePath,n=this.getCleanFileName(e);this.variables.extension=s.substring(1),Object.entries(this.variables).forEach(([r,l])=>{i=i.replace(`\${${r}}`,this.sanitizePath(l))});let a=this.storeFileName,o={...this.variables,originalName:n,random:I(e)};return Object.entries(o).forEach(([r,l])=>{a=a.replace(`\${${r}}`,this.sanitizePath(l))}),a.endsWith(s)||(a+=s),i=this.sanitizePath(i),a=this.sanitizePath(a),`${i}/${a}`}async downloadFile(e,t,s=!1){try{let i=await(0,W.requestUrl)({url:e,headers:{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"},throw:!1,method:"GET"});if(i.status!==200)return{success:!1,error:`Failed to download file: ${i.status} ${i.text}`,localPath:""};let n=this.getExtension(t);if(!n||n===".unknown"){let r=i.headers["content-type"];r&&(n=this.getExtensionFromContentType(r))}let a=await this.getLocalPath(e,t,n),o=a.substring(0,a.lastIndexOf("/"));return await this.plugin.app.vault.adapter.mkdir(o),await this.saveFile(i,a),{success:!0,error:"",localPath:a}}catch(i){return{success:!1,error:`Error downloading file: ${i}`,localPath:""}}}sanitizePath(e){return e.replace(/[\s<>:"\\|?*]/g,"_")}async saveFile(e,t){var s,i,n,a;if(!((n=(i=(s=this.plugin)==null?void 0:s.app)==null?void 0:i.vault)!=null&&n.adapter))throw new Error("App vault adapter not found");if(e.arrayBuffer){await this.plugin.app.vault.adapter.writeBinary(t,e.arrayBuffer);return}if(e.text&&((a=e.headers["content-type"])!=null&&a.includes("application/octet-stream"))){let o=atob(e.text),r=new Array(o.length);for(let c=0;c<o.length;c++)r[c]=o.charCodeAt(c);let l=new Uint8Array(r);await this.plugin.app.vault.adapter.writeBinary(t,l.buffer);return}if(e.text){let r=new TextEncoder().encode(e.text).buffer;await this.plugin.app.vault.adapter.writeBinary(t,r);return}throw new Error("No valid data found in response")}};var M=class{replaceInText(e,t){let s=e;for(let[i,n]of t.entries()){let a=n.split("/").pop()||n,o=new RegExp(`!\\[([^\\]]*)\\]\\(${this.escapeRegExp(i)}\\)`,"g"),r=new RegExp(`(?<!!)\\[([^\\]]*)\\]\\(${this.escapeRegExp(i)}\\)`,"g");o.test(s)?s=s.replace(o,`![$1](${a})`):r.test(s)?s=s.replace(r,`[$1](${a})`):s=s.replace(i,`[${a}](${a})`)}return s}escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}};function O(d){let e=new Date,t=d.split("/").pop()||"untitled";return{path:d,notename:t,date:e.toISOString().split("T")[0],time:e.toISOString().split("T")[1].split(".")[0].replace(/:/g,"-"),originalName:t,random:Y(t),year:e.getFullYear().toString(),month:(e.getMonth()+1).toString().padStart(2,"0"),day:e.getDate().toString().padStart(2,"0"),hour:e.getHours().toString().padStart(2,"0"),minute:e.getMinutes().toString().padStart(2,"0"),second:e.getSeconds().toString().padStart(2,"0")}}function Y(d){let e=0;for(let t=0;t<d.length;t++){let s=d.charCodeAt(t);e=(e<<5)-e+s,e=e&e}return Math.abs(e).toString(36)}var R=class{constructor(e,t){this.plugin=e;this.app=t}async handleDownloadWithOptions(e){new $(this.app,this.plugin,()=>this.handleDownload(),e).open()}async handleDownload(){let e=h.validateSettings(this.plugin.settings);if(!e.isValid){new V.Notice(`Please fix the following issues:
`+e.errors.join(`
`),5e3);return}let t=new L(this.app,this.plugin,async()=>{var s;try{let i=[],n=this.app.workspace.getActiveFile();switch(this.plugin.settings.scope){case"currentFile":i=n?[n]:[];break;case"allFiles":i=this.app.vault.getMarkdownFiles();break;case"currentFolder":if(n){let p=((s=n.parent)==null?void 0:s.path)||"";i=this.app.vault.getMarkdownFiles().filter(g=>{var S;return((S=g.parent)==null?void 0:S.path)===p})}break}let a=0,o=i.length;if(o===0){t.addLog("No documents found in the selected scope.","error");return}t.updateStats({totalNotes:o,processedNotes:0,totalLinks:0,downloadedFiles:0,failedFiles:0});let r=0,l=0,c=0;for(let p of i){t.startDocumentLog(p.path);let g=await this.app.vault.read(p),m=new D(this.plugin.getFinalProcessingExtensions(),this.plugin.settings.presetExtensions).extractFromText(g);if(r+=m.length,t.addLog(`Found ${m.length} links in ${p.path}`,"success","extract"),this.plugin.settings.tasks.length===1&&this.plugin.settings.tasks.includes("extract")){for(let x of m)t.addLog(`Link: ${x.originalLink}`,"info","extract"),t.addDivider();t.updateDocumentProgress(p.path,m.length,m.length,0)}if(this.plugin.settings.tasks.includes("download")){let x=0,z=0,C=new Map;for(let E of m){let b=new P(this.plugin,this.plugin.settings.storePath,O(p.path),this.plugin.settings.storeFileName);t.addDivider(),t.addLog(`File: ${E.originalLink}`,"info","download");let y=await b.downloadFile(E.originalLink,E.fileName,E.isMarkdownImage);y.success?(t.addLog("Status: \u2713 Success","success","download"),t.addLog(`SavedPath: ${y.localPath}`,"success","download"),l++,x++,C.set(E.originalLink,y.localPath)):(t.addLog("Status: \u2717 Failed","error","download"),t.addLog(`Error: ${y.error}`,"error","download"),c++,z++),t.updateDocumentProgress(p.path,m.length,x,z),t.updateStats({totalLinks:r,downloadedFiles:l,failedFiles:c})}if(this.plugin.settings.tasks.includes("replace")&&C.size>0){t.addDivider();let b=new M().replaceInText(g,C);await this.app.fileManager.processFrontMatter(p,y=>{}),await this.app.vault.modify(p,b),t.addLog(`Updated links in ${p.path}`,"success","replace")}}a++,t.updateProgress(a/o*100),t.updateStats({processedNotes:a})}t.addDivider(),t.addLog("Processing current document complete!","success")}catch(i){t.addLog(`Error: ${i.message}`,"error")}});t.open()}async handleSingleDownload(e){this.plugin.settings.scope="singleItem",await this.plugin.saveSettings();let t=h.validateSettings(this.plugin.settings);if(!t.isValid){new V.Notice(`Please fix the following issues:
`+t.errors.join(`
`),5e3);return}let s=new L(this.app,this.plugin,async()=>{s.startDocumentLog(e);let i=new P(this.plugin,this.plugin.settings.storePath,O(e),this.plugin.settings.storeFileName);try{let o=new D(this.plugin.getFinalProcessingExtensions(),this.plugin.settings.presetExtensions).extractFromText(e).length;if(o===0){s.addLog("Status: \u2717 Failed","error"),s.addLog("Error: No valid links found with target extensions","error"),s.updateDocumentProgress(e,0,0,0),s.updateStats({totalNotes:1,processedNotes:1,totalLinks:0,downloadedFiles:0,failedFiles:0});return}let r=await i.downloadFile(e,e.split("/").pop()||"untitled");r.success?(s.addLog("Status: \u2713 Success","success"),s.addLog(`SavedPath: \u2713 ${r.localPath}`,"success"),s.updateDocumentProgress(e,o,1,0),s.updateStats({totalNotes:1,processedNotes:1,totalLinks:o,downloadedFiles:1,failedFiles:0})):(s.addLog("Status: \u2717 Failed","error"),s.addLog(`Error: ${r.error}`,"error"),s.updateDocumentProgress(e,o,0,1),s.updateStats({totalNotes:1,processedNotes:1,totalLinks:o,downloadedFiles:0,failedFiles:1}))}catch(n){s.addLog(`Error downloading attachment: ${n.message}`,"error"),s.updateStats({totalNotes:1,processedNotes:1,totalLinks:0,downloadedFiles:0,failedFiles:1})}});s.open()}};var j=class extends F.Plugin{async onload(){await this.loadSettings(),this.downloadHandler=new R(this,this.app),this.addCommand({id:"local-anything",name:"Download attachments from links",callback:()=>this.downloadHandler.handleDownloadWithOptions()}),this.addCommand({id:"local-anything-use-previous-options",name:"Download attachments from links (use previous options)",callback:()=>this.downloadHandler.handleDownload()}),this.registerEvent(this.app.workspace.on("editor-menu",(t,s,i)=>{if(i instanceof F.MarkdownView){let n=s.getCursor(),a=s.getLine(n.line),o=a.match(/\[([^\]]*)\]\(([^)]+)\)/),r=a.match(/!\[([^\]]*)\]\(([^)]+)\)/);if(o||r){let l=o||r;if(l){let c=l[2],p="";try{let b=(new URL(c).pathname.split(/[?#]/)[0].split("/").pop()||"").match(/\.([^.]+)$/);p=b?"."+b[1].toLowerCase():""}catch(x){p="."+(c.split(".").pop()||"").toLowerCase().split(/[?#]/)[0]}let g=w.image.includes(p),S=this.getFinalProcessingExtensions(),m=S&&S.includes(p);console.debug("URL:",c,"Extension:",p,"Is Image:",g,"Is Preset:",m),(g||m)&&t.addItem(x=>{x.setTitle("Download to local").setIcon("download").onClick(async()=>{this.settings&&new T(this.app,this,c,async()=>{await this.downloadHandler.handleSingleDownload(c)}).open()})})}}}})),this.registerEvent(this.app.workspace.on("file-menu",(t,s)=>{s instanceof F.TFile&&s.extension==="md"&&t.addItem(i=>{i.setTitle("Download files (current note)").setIcon("download").onClick(()=>this.downloadHandler.handleDownloadWithOptions("currentFile"))})})),this.addSettingTab(new N(this.app,this))}async loadSettings(){let t=await this.loadData();this.settings={...H,...t,scope:(t==null?void 0:t.scope)||H.scope||"currentFile"}}async saveSettings(){await this.saveData(this.settings)}getFinalProcessingExtensions(){let t=this.settings.presetExtensions.flatMap(s=>w[s]);return[...new Set([...t,...this.settings.customExtensions])]}};
/* nosourcemap */