watcher_handler.cljs 3.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. (ns frontend.fs.watcher-handler
  2. (:require [clojure.core.async :as async]
  3. [lambdaisland.glogi :as log]
  4. [frontend.handler.file :as file-handler]
  5. [frontend.handler.page :as page-handler]
  6. [frontend.handler.notification :as notification]
  7. [frontend.handler.route :as route-handler]
  8. [cljs-time.coerce :as tc]
  9. [frontend.config :as config]
  10. [frontend.db :as db]
  11. [frontend.state :as state]
  12. [clojure.string :as string]
  13. [frontend.encrypt :as encrypt]
  14. [frontend.db.model :as model]
  15. [frontend.handler.editor :as editor]
  16. [frontend.handler.extract :as extract]
  17. [promesa.core :as p]
  18. [electron.ipc :as ipc]))
  19. (defn- set-missing-block-ids!
  20. [content]
  21. (when (string? content)
  22. (doseq [block-id (extract/extract-all-block-refs content)]
  23. (when-let [block (try
  24. (model/get-block-by-uuid block-id)
  25. (catch js/Error _e
  26. nil))]
  27. (let [id-property (:id (:block/properties block))]
  28. (when-not (= (str id-property) (str block-id))
  29. (editor/set-block-property! block-id "id" block-id)))))))
  30. (defn handle-changed!
  31. [type {:keys [dir path content stat] :as payload}]
  32. (when dir
  33. (let [repo (config/get-local-repo dir)
  34. {:keys [mtime]} stat
  35. db-content (or (db/get-file repo path) "")]
  36. (when (and content (not (encrypt/content-encrypted? content)))
  37. (cond
  38. (= "add" type)
  39. (when-not (db/file-exists? repo path)
  40. (p/let [_ (file-handler/alter-file repo path content {:re-render-root? true
  41. :from-disk? true})]
  42. (set-missing-block-ids! content)
  43. (db/set-file-last-modified-at! repo path mtime)))
  44. (and (= "change" type)
  45. (not (db/file-exists? repo path)))
  46. (js/console.warn "Can't get file in the db: " path)
  47. (and (= "change" type)
  48. (not= (string/trim content) (string/trim db-content))
  49. (not (string/includes? path "logseq/pages-metadata.edn")))
  50. (p/let [
  51. ;; save the previous content in Logseq first and commit it to avoid
  52. ;; any data-loss.
  53. _ (file-handler/alter-file repo path db-content {:re-render-root? false
  54. :reset? false
  55. :skip-compare? true})
  56. _ (ipc/ipc "gitCommitAll" "Save the file from Logseq's database")
  57. _ (file-handler/alter-file repo path content {:re-render-root? true
  58. :skip-compare? true})]
  59. (set-missing-block-ids! content)
  60. (db/set-file-last-modified-at! repo path mtime))
  61. (contains? #{"add" "change" "unlink"} type)
  62. nil
  63. :else
  64. (log/error :fs/watcher-no-handler {:type type
  65. :payload payload})))
  66. ;; return nil, otherwise the entire db will be transfered by ipc
  67. nil)))