gavvvr / obsidian-imgur-plugin

Pastes images right to imgur.com
MIT License
221 stars 58 forks source link

Local file upload from local link messes up current note in case of multiple local references to the same file in original note #94

Open gavvvr opened 2 weeks ago

gavvvr commented 2 weeks ago

This bug is related to feature allowing to convert local image to remote one.

Create a note with the following content:

![[example-local-image.png]]
some plain text
![[example-local-image.png]]

example-local-image.png should exist in vault

Put a cursor on first embedded local image and invoke an action to upload it to Imgur. When finished, the plugin will ask if user would like to replace all local references with remote one. If user agrees, the content of current note will be messed up.

gavvvr commented 2 weeks ago

This issue is related to the fact that metadataCache doesn't instantly get updated after image upload. The mechanism proposing to perform references updates uses outdated metadataCache and messes up the note on attempt to replace 2nd local reference to image, because offsets from stale cache are no longer valid for just edited note: https://github.com/gavvvr/obsidian-imgur-plugin/blob/1c5448485a33fad78b41041a9d418260e01f9c76/src/ImgurPlugin.ts#L298-L302

The potential solution is to replace the following immediate invocation of proposeToReplaceOtherLocalLinksIfAny: https://github.com/gavvvr/obsidian-imgur-plugin/blob/1c5448485a33fad78b41041a9d418260e01f9c76/src/ImgurPlugin.ts#L221-L225

with the event listener that will trigger proposeToReplaceOtherLocalLinksIfAny only when updated metadata cache is ready:

const ref = this.app.metadataCache.on('changed', (file: TFile) => {
  if (file.path !== noteFile.path) return

  this.proposeToReplaceOtherLocalLinksIfAny(imageFile, imageUrl, {
    path: noteFile.path,
    startPosition: start,
  })
  this.app.metadataCache.offref(ref)
})

Unfortunately, in practices it takes more than a second, based on my perception. I'd be happy to apply this solution if there was a way to trigger cache metadata update for given file faster.