obsidian#FileSystemAdapter TypeScript Examples

The following examples show how to use obsidian#FileSystemAdapter. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: main.ts    From obsidian-custom-attachment-location with GNU General Public License v3.0 6 votes vote down vote up
async onload() {
        console.log('loading plugin');

        this.adapter = this.app.vault.adapter as FileSystemAdapter;
        await this.loadSettings();
        this.backupConfigs();

        this.addSettingTab(new CustomAttachmentLocationSettingTab(this.app, this));
        /*
            bind this pointer to handlePaste
            this.registerEvent(this.app.workspace.on('editor-paste', this.handlePaste));
        */
        this.registerEvent(this.app.workspace.on('editor-paste', this.handlePaste.bind(this)));
        this.registerEvent(this.app.workspace.on('editor-drop', this.handleDrop.bind(this)));
        this.registerEvent(this.app.workspace.on('file-open', this.handleFileOpen.bind(this)));

        this.registerEvent(this.app.vault.on('rename', this.handleRename.bind(this)));


    }
Example #2
Source File: InternalModuleFile.ts    From Templater with GNU Affero General Public License v3.0 6 votes vote down vote up
generate_path(): (relative: boolean) => string {
        return (relative = false) => {
            // TODO: Add mobile support
            if (Platform.isMobileApp) {
                return UNSUPPORTED_MOBILE_TEMPLATE;
            }
            if (!(this.app.vault.adapter instanceof FileSystemAdapter)) {
                throw new TemplaterError(
                    "app.vault is not a FileSystemAdapter instance"
                );
            }
            const vault_path = this.app.vault.adapter.getBasePath();

            if (relative) {
                return this.config.target_file.path;
            } else {
                return `${vault_path}/${this.config.target_file.path}`;
            }
        };
    }
Example #3
Source File: UserSystemFunctions.ts    From Templater with GNU Affero General Public License v3.0 6 votes vote down vote up
constructor(app: App, private plugin: TemplaterPlugin) {
        if (
            Platform.isMobileApp ||
            !(app.vault.adapter instanceof FileSystemAdapter)
        ) {
            this.cwd = "";
        } else {
            this.cwd = app.vault.adapter.getBasePath();
            this.exec_promise = promisify(exec);
        }
    }
Example #4
Source File: main.ts    From obsidian-citation-plugin with MIT License 6 votes vote down vote up
/**
   * Resolve a provided library path, allowing for relative paths rooted at
   * the vault directory.
   */
  resolveLibraryPath(rawPath: string): string {
    const vaultRoot =
      this.app.vault.adapter instanceof FileSystemAdapter
        ? this.app.vault.adapter.getBasePath()
        : '/';
    return path.resolve(vaultRoot, rawPath);
  }
Example #5
Source File: settings.ts    From obsidian-citation-plugin with MIT License 6 votes vote down vote up
/**
   * Returns true iff the path exists; displays error as a side-effect
   */
  async checkCitationExportPath(filePath: string): Promise<boolean> {
    this.citationPathLoadingEl.addClass('d-none');

    try {
      await FileSystemAdapter.readLocalFile(
        this.plugin.resolveLibraryPath(filePath),
      );
      this.citationPathErrorEl.addClass('d-none');
    } catch (e) {
      this.citationPathSuccessEl.addClass('d-none');
      this.citationPathErrorEl.removeClass('d-none');
      return false;
    }

    return true;
  }
Example #6
Source File: main.ts    From remotely-save with Apache License 2.0 6 votes vote down vote up
getVaultBasePath() {
    if (this.app.vault.adapter instanceof FileSystemAdapter) {
      // in desktop
      return this.app.vault.adapter.getBasePath().split("?")[0];
    } else {
      // in mobile
      return this.app.vault.adapter.getResourcePath("").split("?")[0];
    }
  }
Example #7
Source File: main.ts    From obsidian-pandoc with MIT License 5 votes vote down vote up
vaultBasePath(): string {
        return (this.app.vault.adapter as FileSystemAdapter).getBasePath();
    }
Example #8
Source File: main.ts    From obsidian-pandoc with MIT License 5 votes vote down vote up
getCurrentFile(): string | null {
        const fileData = this.app.workspace.getActiveFile();
        if (!fileData) return null;
        const adapter = this.app.vault.adapter;
        if (adapter instanceof FileSystemAdapter)
            return adapter.getFullPath(fileData.path);
        return null;
    }
Example #9
Source File: files-manager.ts    From Obsidian_to_Anki with GNU General Public License v3.0 5 votes vote down vote up
async requests_1() {
        let requests: AnkiConnect.AnkiConnectRequest[] = []
        let temp: AnkiConnect.AnkiConnectRequest[] = []
        console.info("Requesting addition of notes into Anki...")
        for (let file of this.ownFiles) {
            temp.push(file.getAddNotes())
        }
        requests.push(AnkiConnect.multi(temp))
        temp = []
        console.info("Requesting card IDs of notes to be edited...")
        for (let file of this.ownFiles) {
            temp.push(file.getNoteInfo())
        }
        requests.push(AnkiConnect.multi(temp))
        temp = []
        console.info("Requesting tag list...")
        requests.push(AnkiConnect.getTags())
        console.info("Requesting update of fields of existing notes")
        for (let file of this.ownFiles) {
            temp.push(file.getUpdateFields())
        }
        requests.push(AnkiConnect.multi(temp))
        temp = []
        console.info("Requesting deletion of notes..")
        for (let file of this.ownFiles) {
            temp.push(file.getDeleteNotes())
        }
        requests.push(AnkiConnect.multi(temp))
        temp = []
        console.info("Requesting addition of media...")
        for (let file of this.ownFiles) {
            const mediaLinks = difference(file.formatter.detectedMedia, this.added_media_set)
            for (let mediaLink of mediaLinks) {
                console.log("Adding media file: ", mediaLink)
                const dataFile = this.app.metadataCache.getFirstLinkpathDest(mediaLink, file.path)
                if (!(dataFile)) {
                    console.warn("Couldn't locate media file ", mediaLink)
                }
                else {
                    // Located successfully, so treat as if we've added the media
                    this.added_media_set.add(mediaLink)
                    const realPath = (this.app.vault.adapter as FileSystemAdapter).getFullPath(dataFile.path)
                    temp.push(
                        AnkiConnect.storeMediaFileByPath(
                            basename(mediaLink),
                            realPath
                        )
                    )
                }
            }
        }
        requests.push(AnkiConnect.multi(temp))
        temp = []
        this.requests_1_result = await AnkiConnect.invoke('multi', {actions: requests})
        await this.parse_requests_1()
    }
Example #10
Source File: main.ts    From obsidian-custom-attachment-location with GNU General Public License v3.0 5 votes vote down vote up
adapter: FileSystemAdapter;
Example #11
Source File: main.ts    From obsidian-citation-plugin with MIT License 5 votes vote down vote up
async loadLibrary(): Promise<Library> {
    console.debug('Citation plugin: Reloading library');
    if (this.settings.citationExportPath) {
      const filePath = this.resolveLibraryPath(
        this.settings.citationExportPath,
      );

      // Unload current library.
      this.library = null;

      return FileSystemAdapter.readLocalFile(filePath)
        .then((buffer) => {
          // If there is a remaining error message, hide it
          this.loadErrorNotifier.hide();

          // Decode file as UTF-8.
          const dataView = new DataView(buffer);
          const decoder = new TextDecoder('utf8');
          const value = decoder.decode(dataView);

          return this.loadWorker.post({
            databaseRaw: value,
            databaseType: this.settings.citationExportFormat,
          });
        })
        .then((entries: EntryData[]) => {
          let adapter: new (data: EntryData) => Entry;
          let idKey: string;

          switch (this.settings.citationExportFormat) {
            case 'biblatex':
              adapter = EntryBibLaTeXAdapter;
              idKey = 'key';
              break;
            case 'csl-json':
              adapter = EntryCSLAdapter;
              idKey = 'id';
              break;
          }

          this.library = new Library(
            Object.fromEntries(
              entries.map((e) => [(e as IIndexable)[idKey], new adapter(e)]),
            ),
          );
          console.debug(
            `Citation plugin: successfully loaded library with ${this.library.size} entries.`,
          );

          return this.library;
        })
        .catch((e) => {
          if (e instanceof WorkerManagerBlocked) {
            // Silently catch WorkerManager error, which will be thrown if the
            // library is already being loaded
            return;
          }

          console.error(e);
          this.loadErrorNotifier.show();

          return null;
        });
    } else {
      console.warn(
        'Citations plugin: citation export path is not set. Please update plugin settings.',
      );
    }
  }
Example #12
Source File: main.ts    From obsidian-jupyter with MIT License 5 votes vote down vote up
onLoadFile(file: TFile): Promise<void> {
		// Get the base path of the vault.
		let adapter = file.vault.adapter;
		if (!(adapter instanceof FileSystemAdapter)) {
			this.contentEl.innerHTML = 'Could not determine notebook path.';
			return null;
		}
		// Convert the file by writing it to a temporary location. Piping unfortunately leads to
		// problems for long lines due to buffer overflows.
		let basePath = adapter.getBasePath();
		let filename = `${basePath}/${file.path}`;
		let htmlPath = `${tmpdir()}/${uuid()}.html`;
		let args = ['-m', 'nbconvert', `--output=${htmlPath}`, '--to=html', filename];
		let child = spawn(this.interpreter, args);

		// Process the output and delete the temporary file.
		child.on('close', (code: number) => {
			if (code) {
				this.contentEl.innerHTML = 'Failed to convert notebook to HTML.';
			} else {
				// Create the frame for rendering.
				let frame = document.createElement('iframe');
				frame.addClass('notebookPreview')
				const html = readFileSync(htmlPath).toString();
				const blob = new Blob([html], {type: 'text/html'});
				frame.src = window.URL.createObjectURL(blob);

				// Insert the frame and hook up to resize events.
				this.contentEl.innerHTML = '';
				this.contentEl.addClass('notebookPreview');
				this.contentEl.appendChild(frame);
				new ResizeObserver((entries) => {
					for (let entry of entries) {
						frame.height = `${entry.contentRect.height - 6}px`;
					}
				}).observe(this.contentEl);
			}
			rm(htmlPath, () => null);
		})
		return null;
	}
Example #13
Source File: main.ts    From obsidian-jupyter with MIT License 5 votes vote down vote up
getBasePath(): string {
		if (this.app.vault.adapter instanceof FileSystemAdapter) {
			return (this.app.vault.adapter as FileSystemAdapter).getBasePath();
		}
		throw new Error('cannot determine base path');
	}
Example #14
Source File: renderer.ts    From obsidian-pandoc with MIT License 4 votes vote down vote up
async function postProcessRenderedHTML(plugin: PandocPlugin, inputFile: string, wrapper: HTMLElement,
    outputFormat: string, parentFiles: string[] = [], css: string = '')
{
    const dirname = path.dirname(inputFile);
    const adapter = plugin.app.vault.adapter as FileSystemAdapter;
    const settings = plugin.settings;
    // Fix <span src="image.png">
    for (let span of Array.from(wrapper.querySelectorAll('span[src$=".png"], span[src$=".jpg"], span[src$=".gif"], span[src$=".jpeg"]'))) {
        span.innerHTML = '';
        span.outerHTML = span.outerHTML.replace(/span/g, 'img');
    }
    // Fix <span class='internal-embed' src='another_note_without_extension'>
    for (let span of Array.from(wrapper.querySelectorAll('span.internal-embed'))) {
        let src = span.getAttribute('src');
        if (src) {
            const subfolder = inputFile.substring(adapter.getBasePath().length);  // TODO: this is messy
            const file = plugin.app.metadataCache.getFirstLinkpathDest(src, subfolder);
            try {
                if (parentFiles.indexOf(file.path) !== -1) {
                    // We've got an infinite recursion on our hands
                    // We should replace the embed with a wikilink
                    // Then our link processing happens afterwards
                    span.outerHTML = `<a href="${file}">${span.innerHTML}</a>`;
                } else {
                    const markdown = await adapter.read(file.path);
                    const newParentFiles = [...parentFiles];
                    newParentFiles.push(inputFile);
                    // TODO: because of this cast, embedded notes won't be able to handle complex plugins (eg DataView)
                    const html = await render(plugin, { data: markdown } as MarkdownView, file.path, outputFormat, newParentFiles);
                    span.outerHTML = html.html;
                }
            } catch (e) {
                // Continue if it can't be loaded
                console.error("Pandoc plugin encountered an error trying to load an embedded note: " + e.toString());
            }
        }
    }
    // Fix <a href="app://obsidian.md/markdown_file_without_extension">
    const prefix = 'app://obsidian.md/';
    for (let a of Array.from(wrapper.querySelectorAll('a'))) {
        if (!a.href.startsWith(prefix)) continue;
        // This is now an internal link (wikilink)
        if (settings.linkStrippingBehaviour === 'link' || outputFormat === 'html') {
            let href = path.join(dirname, a.href.substring(prefix.length));
            if (settings.addExtensionsToInternalLinks.length && a.href.startsWith(prefix)) {
                if (path.extname(href) === '') {
                    const dir = path.dirname(href);
                    const base = path.basename(href);
                    // Be careful to turn [[note#heading]] into note.extension#heading not note#heading.extension
                    const hashIndex = base.indexOf('#');
                    if (hashIndex !== -1) {
                        href = path.join(dir, base.substring(0, hashIndex) + '.' + settings.addExtensionsToInternalLinks + base.substring(hashIndex));
                    } else {
                        href = path.join(dir, base + '.' + settings.addExtensionsToInternalLinks);
                    }
                }
            }
            a.href = href;
        } else if (settings.linkStrippingBehaviour === 'strip') {
            a.outerHTML = '';
        } else if (settings.linkStrippingBehaviour === 'text') {
            a.outerHTML = a.innerText;
        } else if (settings.linkStrippingBehaviour === 'unchanged') {
            a.outerHTML = '[[' + a.outerHTML + ']]';
        }
    }
    // Fix <img src="app://obsidian.md/image.png">
    // Note: this will throw errors when Obsidian tries to load images with a (now invalid) src
    // These errors can be safely ignored
    if (outputFormat !== 'html') {
        for (let img of Array.from(wrapper.querySelectorAll('img'))) {
            if (img.src.startsWith(prefix) && img.getAttribute('data-touched') !== 'true') {
                img.src = adapter.getFullPath(img.src.substring(prefix.length));
                img.setAttribute('data-touched', 'true');
            }
        }
    }
    // Remove YAML frontmatter from the output if desired
    if (!settings.displayYAMLFrontmatter) {
        Array.from(wrapper.querySelectorAll('.frontmatter, .frontmatter-container'))
            .forEach(el => wrapper.removeChild(el));
    }
    // Fix Mermaid.js diagrams
    for (let svg of Array.from(wrapper.querySelectorAll('svg'))) {
        // Insert the CSS variables as a CSS string (even if the user doesn't want CSS injected; Mermaid diagrams look terrible otherwise)
        // TODO: it injects light theme CSS, do we want this?
        let style: HTMLStyleElement = svg.querySelector('style') || svg.appendChild(document.createElement('style'));
        style.innerHTML += css;
        // Inject a marker (arrowhead) for Mermaid.js diagrams and use it at the end of paths
        svg.innerHTML += `"<marker id="mermaid_arrowhead" viewBox="0 0 10 10" refX="9" refY="5" markerUnits="strokeWidth" markerWidth="8" markerHeight="6" orient="auto"><path d="M 0 0 L 10 5 L 0 10 z" class="arrowheadPath" style="stroke-width: 1; stroke-dasharray: 1, 0;"></path></marker>"`;
        svg.innerHTML = svg.innerHTML.replace(/app:\/\/obsidian\.md\/index\.html#arrowhead\d*/g, "#mermaid_arrowhead");
        // If the output isn't HTML, replace the SVG with a PNG for compatibility
        if (outputFormat !== 'html') {
            const scale = settings.highDPIDiagrams ? 2 : 1;
            const png = await convertSVGToPNG(svg, scale);
            svg.parentNode.replaceChild(png, svg);
        }
    }
}