events.cljs 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885
  1. (ns frontend.handler.events
  2. "System-component-like ns that defines named events and listens on a
  3. core.async channel to handle them. Any part of the system can dispatch
  4. one of these events using state/pub-event!"
  5. (:refer-clojure :exclude [run!])
  6. (:require ["@capacitor/filesystem" :refer [Directory Filesystem]]
  7. [clojure.core.async :as async]
  8. [clojure.core.async.interop :refer [p->c]]
  9. [clojure.set :as set]
  10. [clojure.string :as string]
  11. [datascript.core :as d]
  12. [frontend.commands :as commands]
  13. [frontend.components.diff :as diff]
  14. [frontend.components.git :as git-component]
  15. [frontend.components.plugins :as plugin]
  16. [frontend.components.search :as component-search]
  17. [frontend.components.shell :as shell]
  18. [frontend.config :as config]
  19. [frontend.context.i18n :refer [t]]
  20. [frontend.db :as db]
  21. [frontend.db.conn :as conn]
  22. [frontend.db.model :as db-model]
  23. [frontend.db.persist :as db-persist]
  24. [frontend.extensions.srs :as srs]
  25. [frontend.fs :as fs]
  26. [frontend.fs.capacitor-fs :as capacitor-fs]
  27. [frontend.fs.nfs :as nfs]
  28. [frontend.fs.sync :as sync]
  29. [frontend.fs.watcher-handler :as fs-watcher]
  30. [frontend.handler.common :as common-handler]
  31. [frontend.handler.editor :as editor-handler]
  32. [frontend.handler.file :as file-handler]
  33. [frontend.handler.notification :as notification]
  34. [frontend.handler.page :as page-handler]
  35. [frontend.handler.plugin :as plugin-handler]
  36. [frontend.handler.repo :as repo-handler]
  37. [frontend.handler.repo-config :as repo-config-handler]
  38. [frontend.handler.route :as route-handler]
  39. [frontend.handler.search :as search-handler]
  40. [frontend.handler.ui :as ui-handler]
  41. [frontend.handler.user :as user-handler]
  42. [frontend.handler.web.nfs :as nfs-handler]
  43. [frontend.mobile.core :as mobile]
  44. [frontend.mobile.util :as mobile-util]
  45. [frontend.mobile.graph-picker :as graph-picker]
  46. [frontend.modules.instrumentation.posthog :as posthog]
  47. [frontend.modules.outliner.file :as outliner-file]
  48. [frontend.modules.shortcut.core :as st]
  49. [frontend.search :as search]
  50. [frontend.state :as state]
  51. [frontend.ui :as ui]
  52. [frontend.util :as util]
  53. [frontend.util.persist-var :as persist-var]
  54. [frontend.handler.file-sync :as file-sync-handler]
  55. [frontend.components.file-sync :as file-sync]
  56. [frontend.components.encryption :as encryption]
  57. [frontend.components.conversion :as conversion-component]
  58. [goog.dom :as gdom]
  59. [logseq.db.schema :as db-schema]
  60. [promesa.core :as p]
  61. [rum.core :as rum]
  62. [logseq.graph-parser.config :as gp-config]))
  63. ;; TODO: should we move all events here?
  64. (defmulti handle first)
  65. (defn- file-sync-restart! []
  66. (async/go (async/<! (p->c (persist-var/load-vars)))
  67. (async/<! (sync/<sync-stop))
  68. (some-> (sync/<sync-start) async/<!)))
  69. (defn- file-sync-stop! []
  70. (async/go (async/<! (p->c (persist-var/load-vars)))
  71. (async/<! (sync/<sync-stop))))
  72. (defmethod handle :user/login [[_]]
  73. (state/set-state! [:ui/loading? :login] false)
  74. (async/go
  75. (let [result (async/<! (sync/<user-info sync/remoteapi))]
  76. (cond
  77. (instance? ExceptionInfo result)
  78. nil
  79. (map? result)
  80. (do
  81. (state/set-state! :user/info result)
  82. (let [status (if (user-handler/alpha-or-beta-user?) :welcome :unavailable)]
  83. (when (and (= status :welcome) (user-handler/logged-in?))
  84. (file-sync-handler/set-sync-enabled! true)
  85. (async/<! (file-sync-handler/load-session-graphs))
  86. (p/let [repos (repo-handler/refresh-repos!)]
  87. (when-let [repo (state/get-current-repo)]
  88. (when (some #(and (= (:url %) repo)
  89. (vector? (:sync-meta %))
  90. (util/uuid-string? (first (:sync-meta %)))
  91. (util/uuid-string? (second (:sync-meta %)))) repos)
  92. (sync/<sync-start)))))
  93. (ui-handler/re-render-root!)
  94. (file-sync/maybe-onboarding-show status)))))))
  95. (defmethod handle :user/logout [[_]]
  96. (file-sync-handler/reset-session-graphs)
  97. (sync/remove-all-pwd!)
  98. (file-sync-handler/reset-user-state!))
  99. (defmethod handle :graph/added [[_ repo {:keys [empty-graph?]}]]
  100. (db/set-key-value repo :ast/version db-schema/ast-version)
  101. (search-handler/rebuild-indices!)
  102. (db/persist! repo)
  103. (plugin-handler/hook-plugin-app :graph-after-indexed {:repo repo :empty-graph? empty-graph?})
  104. (when (state/setups-picker?)
  105. (if empty-graph?
  106. (route-handler/redirect! {:to :import :query-params {:from "picker"}})
  107. (route-handler/redirect-to-home!)))
  108. (when-let [dir-name (config/get-repo-dir repo)]
  109. (fs/watch-dir! dir-name))
  110. (file-sync-restart!))
  111. (defmethod handle :graph/unlinked [repo current-repo]
  112. (when (= (:url repo) current-repo)
  113. (file-sync-restart!)))
  114. ;; FIXME: awful multi-arty function.
  115. ;; Should use a `-impl` function instead of the awful `skip-ios-check?` param with nested callback.
  116. (defn- graph-switch
  117. ([graph]
  118. (graph-switch graph false))
  119. ([graph skip-ios-check?]
  120. (if (and (mobile-util/native-ios?) (not skip-ios-check?))
  121. (state/pub-event! [:validate-appId graph-switch graph])
  122. (do
  123. (state/set-current-repo! graph)
  124. ;; load config
  125. (repo-config-handler/restore-repo-config! graph)
  126. (when-not (= :draw (state/get-current-route))
  127. (route-handler/redirect-to-home!))
  128. (when-let [dir-name (config/get-repo-dir graph)]
  129. (fs/watch-dir! dir-name))
  130. (srs/update-cards-due-count!)
  131. (state/pub-event! [:graph/ready graph])
  132. (file-sync-restart!)))))
  133. ;; Parameters for the `persist-db` function, to show the notification messages
  134. (def persist-db-noti-m
  135. {:before #(notification/show!
  136. (ui/loading (t :graph/persist))
  137. :warning)
  138. :on-error #(notification/show!
  139. (t :graph/persist-error)
  140. :error)})
  141. (defn- graph-switch-on-persisted
  142. "Logic for keeping db sync when switching graphs
  143. Only works for electron
  144. graph: the target graph to switch to"
  145. [graph {:keys [persist?]}]
  146. (let [current-repo (state/get-current-repo)]
  147. (p/do!
  148. (when persist?
  149. (when (util/electron?)
  150. (p/do!
  151. (repo-handler/persist-db! current-repo persist-db-noti-m)
  152. (repo-handler/broadcast-persist-db! graph))))
  153. (repo-handler/restore-and-setup-repo! graph)
  154. (graph-switch graph)
  155. state/set-state! :sync-graph/init? false)))
  156. (defmethod handle :graph/switch [[_ graph opts]]
  157. (let [opts (if (false? (:persist? opts)) opts (assoc opts :persist? true))]
  158. (if (or (not (false? (get @outliner-file/*writes-finished? graph)))
  159. (:sync-graph/init? @state/state))
  160. (graph-switch-on-persisted graph opts)
  161. (notification/show!
  162. "Please wait seconds until all changes are saved for the current graph."
  163. :warning))))
  164. (defmethod handle :graph/pull-down-remote-graph [[_ graph dir-name]]
  165. (if (mobile-util/native-ios?)
  166. (when-let [graph-name (or dir-name (:GraphName graph))]
  167. (let [graph-name (util/safe-sanitize-file-name graph-name)]
  168. (if (string/blank? graph-name)
  169. (notification/show! "Illegal graph folder name.")
  170. ;; Create graph directory under Logseq document folder (local)
  171. (when-let [root (state/get-local-container-root-url)]
  172. (let [graph-path (graph-picker/validate-graph-dirname root graph-name)]
  173. (->
  174. (p/let [exists? (fs/dir-exists? graph-path)]
  175. (let [overwrite? (if exists?
  176. (js/confirm (str "There's already a directory with the name \"" graph-name "\", do you want to overwrite it? Make sure to backup it first if you're not sure about it."))
  177. true)]
  178. (if overwrite?
  179. (p/let [_ (fs/mkdir-if-not-exists graph-path)]
  180. (nfs-handler/ls-dir-files-with-path!
  181. graph-path
  182. {:ok-handler (fn []
  183. (file-sync-handler/init-remote-graph graph-path graph)
  184. (js/setTimeout (fn [] (repo-handler/refresh-repos!)) 200))}))
  185. (let [graph-name (-> (js/prompt "Please specify a new directory name to download the graph:")
  186. str
  187. string/trim)]
  188. (when-not (string/blank? graph-name)
  189. (state/pub-event! [:graph/pull-down-remote-graph graph graph-name]))))))
  190. (p/catch (fn [^js e]
  191. (notification/show! (str e) :error)
  192. (js/console.error e)))))))))
  193. (state/set-modal!
  194. (file-sync/pick-dest-to-sync-panel graph)
  195. {:center? true})))
  196. (defmethod handle :graph/pick-page-histories [[_ graph-uuid page-name]]
  197. (state/set-modal!
  198. (file-sync/pick-page-histories-panel graph-uuid page-name)
  199. {:id :page-histories :label "modal-page-histories"}))
  200. (defmethod handle :graph/open-new-window [[_ev repo]]
  201. (p/let [current-repo (state/get-current-repo)
  202. target-repo (or repo current-repo)
  203. _ (repo-handler/persist-db! current-repo persist-db-noti-m) ;; FIXME: redundant when opening non-current-graph window
  204. _ (when-not (= current-repo target-repo)
  205. (repo-handler/broadcast-persist-db! repo))]
  206. (ui-handler/open-new-window! repo)))
  207. (defmethod handle :graph/migrated [[_ _repo]]
  208. (js/alert "Graph migrated."))
  209. (defmethod handle :graph/save [_]
  210. (repo-handler/persist-db! (state/get-current-repo)
  211. {:before #(notification/show!
  212. (ui/loading (t :graph/save))
  213. :warning)
  214. :on-success #(do
  215. (notification/clear-all!)
  216. (notification/show!
  217. (t :graph/save-success)
  218. :success))
  219. :on-error #(notification/show!
  220. (t :graph/save-error)
  221. :error)}))
  222. (defn get-local-repo
  223. []
  224. (when-let [repo (state/get-current-repo)]
  225. (when (config/local-db? repo)
  226. repo)))
  227. (defn ask-permission
  228. [repo]
  229. (when
  230. (and (not (util/electron?))
  231. (not (mobile-util/native-platform?)))
  232. (fn [close-fn]
  233. [:div
  234. [:p
  235. "Grant native filesystem permission for directory: "
  236. [:b (config/get-local-dir repo)]]
  237. (ui/button
  238. "Grant"
  239. :class "ui__modal-enter"
  240. :on-click (fn []
  241. (nfs/check-directory-permission! repo)
  242. (close-fn)))])))
  243. (defmethod handle :modal/nfs-ask-permission []
  244. (when-let [repo (get-local-repo)]
  245. (state/set-modal! (ask-permission repo))))
  246. (defonce *query-properties (atom {}))
  247. (rum/defc query-properties-settings-inner < rum/reactive
  248. {:will-unmount (fn [state]
  249. (reset! *query-properties {})
  250. state)}
  251. [block shown-properties all-properties _close-fn]
  252. (let [query-properties (rum/react *query-properties)]
  253. [:div.p-4
  254. [:div.font-bold "Properties settings for this query:"]
  255. (for [property all-properties]
  256. (let [property-value (get query-properties property)
  257. shown? (if (nil? property-value)
  258. (contains? shown-properties property)
  259. property-value)]
  260. [:div.flex.flex-row.m-2.justify-between.align-items
  261. [:div (name property)]
  262. [:div.mt-1 (ui/toggle shown?
  263. (fn []
  264. (let [value (not shown?)]
  265. (swap! *query-properties assoc property value)
  266. (editor-handler/set-block-query-properties!
  267. (:block/uuid block)
  268. all-properties
  269. property
  270. value)))
  271. true)]]))]))
  272. (defn query-properties-settings
  273. [block shown-properties all-properties]
  274. (fn [close-fn]
  275. (query-properties-settings-inner block shown-properties all-properties close-fn)))
  276. (defmethod handle :modal/set-query-properties [[_ block all-properties]]
  277. (let [block-properties (some-> (get-in block [:block/properties :query-properties])
  278. (common-handler/safe-read-string "Parsing query properties failed"))
  279. shown-properties (if (seq block-properties)
  280. (set block-properties)
  281. (set all-properties))
  282. shown-properties (set/intersection (set all-properties) shown-properties)]
  283. (state/set-modal! (query-properties-settings block shown-properties all-properties)
  284. {:center? true})))
  285. (defmethod handle :modal/show-cards [_]
  286. (state/set-modal! srs/global-cards {:id :srs
  287. :label "flashcards__cp"}))
  288. (defmethod handle :modal/show-instruction [_]
  289. (state/set-modal! capacitor-fs/instruction {:id :instruction
  290. :label "instruction__cp"}))
  291. (defmethod handle :modal/show-themes-modal [_]
  292. (plugin/open-select-theme!))
  293. (rum/defc modal-output
  294. [content]
  295. content)
  296. (defmethod handle :modal/show [[_ content]]
  297. (state/set-modal! #(modal-output content)))
  298. (defmethod handle :modal/set-git-username-and-email [[_ _content]]
  299. (state/set-modal! git-component/set-git-username-and-email))
  300. (defmethod handle :page/title-property-changed [[_ old-title new-title]]
  301. (page-handler/rename! old-title new-title))
  302. (defmethod handle :page/create [[_ page-name opts]]
  303. (page-handler/create! page-name opts))
  304. (defmethod handle :page/create-today-journal [[_ _repo]]
  305. (p/let [_ (page-handler/create-today-journal!)]
  306. (ui-handler/re-render-root!)))
  307. (defmethod handle :file/not-matched-from-disk [[_ path disk-content db-content]]
  308. (state/clear-edit!)
  309. (when-let [repo (state/get-current-repo)]
  310. (when (and disk-content db-content
  311. (not= (util/trim-safe disk-content) (util/trim-safe db-content)))
  312. (state/set-modal! #(diff/local-file repo path disk-content db-content)
  313. {:label "diff__cp"}))))
  314. (defmethod handle :modal/display-file-version [[_ path content hash]]
  315. (state/set-modal! #(git-component/file-specific-version path hash content)))
  316. ;; Hook on a graph is ready to be shown to the user.
  317. ;; It's different from :graph/resotred, as :graph/restored is for window reloaded
  318. (defmethod handle :graph/ready
  319. [[_ repo]]
  320. (when (config/local-db? repo)
  321. (p/let [dir (config/get-repo-dir repo)
  322. dir-exists? (fs/dir-exists? dir)]
  323. (when-not dir-exists?
  324. (state/pub-event! [:graph/dir-gone dir]))))
  325. ;; FIXME: an ugly implementation for redirecting to page on new window is restored
  326. (repo-handler/graph-ready! repo))
  327. (defmethod handle :notification/show [[_ {:keys [content status clear?]}]]
  328. (notification/show! content status clear?))
  329. (defmethod handle :command/run [_]
  330. (when (util/electron?)
  331. (state/set-modal! shell/shell)))
  332. (defmethod handle :go/search [_]
  333. (state/set-modal! component-search/search-modal
  334. {:fullscreen? false
  335. :close-btn? false}))
  336. (defmethod handle :go/plugins [_]
  337. (plugin/open-plugins-modal!))
  338. (defmethod handle :go/plugins-waiting-lists [_]
  339. (plugin/open-waiting-updates-modal!))
  340. (defmethod handle :go/plugins-from-file [[_ plugins]]
  341. (plugin/open-plugins-from-file-modal! plugins))
  342. (defmethod handle :go/plugins-settings [[_ pid nav? title]]
  343. (if pid
  344. (do
  345. (state/set-state! :plugin/focused-settings pid)
  346. (state/set-state! :plugin/navs-settings? (not (false? nav?)))
  347. (plugin/open-focused-settings-modal! title))
  348. (state/close-sub-modal! "ls-focused-settings-modal")))
  349. (defmethod handle :go/proxy-settings [[_ agent-opts]]
  350. (state/set-sub-modal!
  351. (fn [_] (plugin/user-proxy-settings-panel agent-opts))
  352. {:id :https-proxy-panel :center? true}))
  353. (defmethod handle :redirect-to-home [_]
  354. (page-handler/create-today-journal!))
  355. (defmethod handle :instrument [[_ {:keys [type payload]}]]
  356. (posthog/capture type payload))
  357. (defmethod handle :exec-plugin-cmd [[_ {:keys [pid cmd action]}]]
  358. (commands/exec-plugin-simple-command! pid cmd action))
  359. (defmethod handle :shortcut-handler-refreshed [[_]]
  360. (when-not @st/*inited?
  361. (reset! st/*inited? true)
  362. (st/consume-pending-shortcuts!)))
  363. (defmethod handle :mobile/keyboard-will-show [[_ keyboard-height]]
  364. (let [main-node (util/app-scroll-container-node)]
  365. (state/set-state! :mobile/show-tabbar? false)
  366. (state/set-state! :mobile/show-toolbar? true)
  367. (state/set-state! :mobile/show-action-bar? false)
  368. (when (= (state/sub :editor/record-status) "RECORDING")
  369. (state/set-state! :mobile/show-recording-bar? true))
  370. (when (mobile-util/native-ios?)
  371. (reset! util/keyboard-height keyboard-height)
  372. (set! (.. main-node -style -marginBottom) (str keyboard-height "px"))
  373. (when-let [left-sidebar-node (gdom/getElement "left-sidebar")]
  374. (set! (.. left-sidebar-node -style -bottom) (str keyboard-height "px")))
  375. (when-let [right-sidebar-node (gdom/getElementByClass "sidebar-item-list")]
  376. (set! (.. right-sidebar-node -style -paddingBottom) (str (+ 150 keyboard-height) "px")))
  377. (when-let [card-preview-el (js/document.querySelector ".cards-review")]
  378. (set! (.. card-preview-el -style -marginBottom) (str keyboard-height "px")))
  379. (when-let [card-preview-el (js/document.querySelector ".encryption-password")]
  380. (set! (.. card-preview-el -style -marginBottom) (str keyboard-height "px")))
  381. (js/setTimeout (fn []
  382. (when-let [toolbar (.querySelector main-node "#mobile-editor-toolbar")]
  383. (set! (.. toolbar -style -bottom) (str keyboard-height "px"))))
  384. 100))))
  385. (defmethod handle :mobile/keyboard-will-hide [[_]]
  386. (let [main-node (util/app-scroll-container-node)]
  387. (state/set-state! :mobile/show-toolbar? false)
  388. (state/set-state! :mobile/show-tabbar? true)
  389. (when (= (state/sub :editor/record-status) "RECORDING")
  390. (state/set-state! :mobile/show-recording-bar? false))
  391. (when (mobile-util/native-ios?)
  392. (when-let [card-preview-el (js/document.querySelector ".cards-review")]
  393. (set! (.. card-preview-el -style -marginBottom) "0px"))
  394. (when-let [card-preview-el (js/document.querySelector ".encryption-password")]
  395. (set! (.. card-preview-el -style -marginBottom) "0px"))
  396. (set! (.. main-node -style -marginBottom) "0px")
  397. (when-let [left-sidebar-node (gdom/getElement "left-sidebar")]
  398. (set! (.. left-sidebar-node -style -bottom) "0px"))
  399. (when-let [right-sidebar-node (gdom/getElementByClass "sidebar-item-list")]
  400. (set! (.. right-sidebar-node -style -paddingBottom) "150px")))))
  401. (defn update-file-path [deprecated-repo current-repo deprecated-app-id current-app-id]
  402. (let [files (db-model/get-files-entity deprecated-repo)
  403. conn (conn/get-db deprecated-repo false)
  404. tx (mapv (fn [[id path]]
  405. (let [new-path (string/replace path deprecated-app-id current-app-id)]
  406. {:db/id id
  407. :file/path new-path}))
  408. files)]
  409. (d/transact! conn tx)
  410. (reset! conn/conns
  411. (update-keys @conn/conns
  412. (fn [key] (if (string/includes? key deprecated-repo)
  413. (string/replace key deprecated-repo current-repo)
  414. key))))))
  415. (defn get-ios-app-id
  416. [repo-url]
  417. (when repo-url
  418. (let [app-id (-> (first (string/split repo-url "/Documents"))
  419. (string/split "/")
  420. last)]
  421. app-id)))
  422. (defmethod handle :validate-appId [[_ graph-switch-f graph]]
  423. (when-let [deprecated-repo (or graph (state/get-current-repo))]
  424. ;; Installation is not changed for iCloud
  425. (if (mobile-util/iCloud-container-path? deprecated-repo)
  426. (when graph-switch-f
  427. (graph-switch-f graph true)
  428. (state/pub-event! [:graph/ready (state/get-current-repo)]))
  429. (p/let [deprecated-app-id (get-ios-app-id deprecated-repo)
  430. current-document-url (.getUri Filesystem #js {:path ""
  431. :directory (.-Documents Directory)})
  432. current-app-id (-> (js->clj current-document-url :keywordize-keys true)
  433. get-ios-app-id)]
  434. (if (= deprecated-app-id current-app-id)
  435. (when graph-switch-f (graph-switch-f graph true))
  436. (do
  437. (file-sync-stop!)
  438. (.unwatch mobile-util/fs-watcher)
  439. (let [current-repo (string/replace deprecated-repo deprecated-app-id current-app-id)
  440. current-repo-dir (config/get-repo-dir current-repo)]
  441. (try
  442. (update-file-path deprecated-repo current-repo deprecated-app-id current-app-id)
  443. (db-persist/delete-graph! deprecated-repo)
  444. (search/remove-db! deprecated-repo)
  445. (state/delete-repo! {:url deprecated-repo})
  446. (state/add-repo! {:url current-repo :nfs? true})
  447. (catch :default e
  448. (js/console.error e)))
  449. (state/set-current-repo! current-repo)
  450. (db/listen-and-persist! current-repo)
  451. (db/persist-if-idle! current-repo)
  452. (repo-config-handler/restore-repo-config! current-repo)
  453. (.watch mobile-util/fs-watcher #js {:path current-repo-dir})
  454. (when graph-switch-f (graph-switch-f current-repo true))
  455. (file-sync-restart!))))
  456. (state/pub-event! [:graph/ready (state/get-current-repo)])))))
  457. (defmethod handle :plugin/consume-updates [[_ id pending? updated?]]
  458. (let [downloading? (:plugin/updates-downloading? @state/state)]
  459. (when-let [coming (and (not downloading?)
  460. (get-in @state/state [:plugin/updates-coming id]))]
  461. (let [error-code (:error-code coming)
  462. error-code (if (= error-code (str :no-new-version)) nil error-code)]
  463. (when (or pending? (not error-code))
  464. (notification/show!
  465. (str "[Checked]<" (:title coming) "> " error-code)
  466. (if error-code :error :success)))))
  467. (if (and updated? downloading?)
  468. ;; try to start consume downloading item
  469. (if-let [n (state/get-next-selected-coming-update)]
  470. (plugin-handler/check-or-update-marketplace-plugin
  471. (assoc n :only-check false :error-code nil)
  472. (fn [^js e] (js/console.error "[Download Err]" n e)))
  473. (plugin-handler/close-updates-downloading))
  474. ;; try to start consume pending item
  475. (if-let [n (second (first (:plugin/updates-pending @state/state)))]
  476. (plugin-handler/check-or-update-marketplace-plugin
  477. (assoc n :only-check true :error-code nil)
  478. (fn [^js e]
  479. (notification/show! (.toString e) :error)
  480. (js/console.error "[Check Err]" n e)))
  481. ;; try to open waiting updates list
  482. (when (and pending? (seq (state/all-available-coming-updates)))
  483. (plugin/open-waiting-updates-modal!))))))
  484. (defmethod handle :plugin/hook-db-tx [[_ {:keys [blocks tx-data tx-meta] :as payload}]]
  485. (when-let [payload (and (seq blocks)
  486. (merge payload {:tx-data (map #(into [] %) tx-data)
  487. :tx-meta (dissoc tx-meta :editor-cursor)}))]
  488. (plugin-handler/hook-plugin-db :changed payload)
  489. (plugin-handler/hook-plugin-block-changes payload)))
  490. (defmethod handle :plugin/loader-perf-tip [[_ {:keys [^js o _s _e]}]]
  491. (when-let [opts (.-options o)]
  492. (notification/show!
  493. (plugin/perf-tip-content (.-id o) (.-name opts) (.-url opts))
  494. :warning false (.-id o))))
  495. (defmethod handle :backup/broken-config [[_ repo content]]
  496. (when (and repo content)
  497. (let [path (config/get-repo-config-path)
  498. broken-path (string/replace path "/config.edn" "/broken-config.edn")]
  499. (p/let [_ (fs/write-file! repo (config/get-repo-dir repo) broken-path content {})
  500. _ (file-handler/alter-file repo path config/config-default-content {:skip-compare? true})]
  501. (notification/show!
  502. [:p.content
  503. "It seems that your config.edn is broken. We've restored it with the default content and saved the previous content to the file logseq/broken-config.edn."]
  504. :warning
  505. false)))))
  506. (defmethod handle :file-watcher/changed [[_ ^js event]]
  507. (let [type (.-event event)
  508. payload (-> event
  509. (js->clj :keywordize-keys true)
  510. (update :path (fn [path]
  511. (when (string? path) (capacitor-fs/remove-private-part path)))))]
  512. (fs-watcher/handle-changed! type payload)
  513. (when (file-sync-handler/enable-sync?)
  514. (sync/file-watch-handler type payload))))
  515. (defmethod handle :rebuild-slash-commands-list [[_]]
  516. (page-handler/rebuild-slash-commands-list!))
  517. (defmethod handle :shortcut/refresh [[_]]
  518. (st/refresh!))
  519. (defn- refresh-cb []
  520. (page-handler/create-today-journal!)
  521. (file-sync-restart!))
  522. (defmethod handle :graph/ask-for-re-fresh [_]
  523. (handle
  524. [:modal/show
  525. [:div {:style {:max-width 700}}
  526. [:p (t :sync-from-local-changes-detected)]
  527. (ui/button
  528. (t :yes)
  529. :autoFocus "on"
  530. :class "ui__modal-enter"
  531. :large? true
  532. :on-click (fn []
  533. (state/close-modal!)
  534. (nfs-handler/refresh! (state/get-current-repo) refresh-cb)))]]))
  535. (defmethod handle :sync/create-remote-graph [[_ current-repo]]
  536. (let [graph-name (js/decodeURI (util/node-path.basename current-repo))]
  537. (async/go
  538. (async/<! (sync/<sync-stop))
  539. (state/set-state! [:ui/loading? :graph/create-remote?] true)
  540. (when-let [GraphUUID (get (async/<! (file-sync-handler/create-graph graph-name)) 2)]
  541. (async/<! (sync/<sync-start))
  542. (state/set-state! [:ui/loading? :graph/create-remote?] false)
  543. ;; update existing repo
  544. (state/set-repos! (map (fn [r]
  545. (if (= (:url r) current-repo)
  546. (assoc r
  547. :GraphUUID GraphUUID
  548. :GraphName graph-name
  549. :remote? true)
  550. r))
  551. (state/get-repos)))))))
  552. (defmethod handle :graph/re-index [[_]]
  553. ;; Ensure the graph only has ONE window instance
  554. (repo-handler/re-index!
  555. nfs-handler/rebuild-index!
  556. #(do (page-handler/create-today-journal!)
  557. (file-sync-restart!))))
  558. (defmethod handle :graph/ask-for-re-index [[_ *multiple-windows? ui]]
  559. ;; *multiple-windows? - if the graph is opened in multiple windows, boolean atom
  560. ;; ui - custom message to show on asking for re-index
  561. (if (and (util/atom? *multiple-windows?) @*multiple-windows?)
  562. (handle
  563. [:modal/show
  564. [:div
  565. (when (not (nil? ui)) ui)
  566. [:p (t :re-index-multiple-windows-warning)]]])
  567. (handle
  568. [:modal/show
  569. [:div {:style {:max-width 700}}
  570. (when (not (nil? ui)) ui)
  571. [:p (t :re-index-discard-unsaved-changes-warning)]
  572. (ui/button
  573. (t :yes)
  574. :autoFocus "on"
  575. :class "ui__modal-enter"
  576. :large? true
  577. :on-click (fn []
  578. (state/close-modal!)
  579. (state/pub-event! [:graph/re-index])))]])))
  580. (defmethod handle :modal/remote-encryption-input-pw-dialog [[_ repo-url remote-graph-info type opts]]
  581. (state/set-modal!
  582. (encryption/input-password
  583. repo-url nil (merge
  584. (assoc remote-graph-info
  585. :type (or type :create-pwd-remote)
  586. :repo repo-url)
  587. opts))
  588. {:center? true :close-btn? false :close-backdrop? false}))
  589. (defmethod handle :journal/insert-template [[_ page-name]]
  590. (let [page-name (util/page-name-sanity-lc page-name)]
  591. (when-let [page (db/pull [:block/name page-name])]
  592. (when (db/page-empty? (state/get-current-repo) page-name)
  593. (when-let [template (state/get-default-journal-template)]
  594. (editor-handler/insert-template!
  595. nil
  596. template
  597. {:target page}))))))
  598. (defmethod handle :editor/set-org-mode-heading [[_ block heading]]
  599. (when-let [id (:block/uuid block)]
  600. (editor-handler/set-heading! id :org heading)))
  601. (defmethod handle :file-sync-graph/restore-file [[_ graph page-entity content]]
  602. (when (db/get-db graph)
  603. (let [file (:block/file page-entity)]
  604. (when-let [path (:file/path file)]
  605. (when (and (not= content (:file/content file))
  606. (:file/content file))
  607. (sync/add-new-version-file graph path (:file/content file)))
  608. (p/let [_ (file-handler/alter-file graph
  609. path
  610. content
  611. {:re-render-root? true
  612. :skip-compare? true})]
  613. (state/close-modal!)
  614. (route-handler/redirect! {:to :page
  615. :path-params {:name (:block/name page-entity)}}))))))
  616. (defmethod handle :file-sync/onboarding-tip [[_ type opts]]
  617. (let [type (keyword type)]
  618. (state/set-modal!
  619. (file-sync/make-onboarding-panel type)
  620. (merge {:close-btn? false
  621. :center? true
  622. :close-backdrop? (not= type :welcome)} opts))))
  623. (defmethod handle :file-sync/maybe-onboarding-show [[_ type]]
  624. (file-sync/maybe-onboarding-show type))
  625. (defmethod handle :file-sync/storage-exceed-limit [[_]]
  626. (notification/show! "file sync storage exceed limit" :warning false)
  627. (file-sync-stop!))
  628. (defmethod handle :file-sync/graph-count-exceed-limit [[_]]
  629. (notification/show! "file sync graph count exceed limit" :warning false)
  630. (file-sync-stop!))
  631. (defmethod handle :graph/restored [[_ _graph]]
  632. (mobile/init!)
  633. (when-not (mobile-util/native-ios?)
  634. (state/pub-event! [:graph/ready (state/get-current-repo)])))
  635. (defmethod handle :whiteboard-link [[_ shapes]]
  636. (route-handler/go-to-search! :whiteboard/link)
  637. (state/set-state! :whiteboard/linked-shapes shapes))
  638. (defmethod handle :whiteboard-go-to-link [[_ link]]
  639. (route-handler/redirect! {:to :whiteboard
  640. :path-params {:name link}}))
  641. (defmethod handle :graph/dir-gone [[_ dir]]
  642. (state/pub-event! [:notification/show
  643. {:content (str "The directory " dir " has been renamed or deleted, the editor will be disabled for this graph, you can unlink the graph.")
  644. :status :error
  645. :clear? false}])
  646. (state/update-state! :file/unlinked-dirs (fn [dirs] (conj dirs dir))))
  647. (defmethod handle :graph/dir-back [[_ repo dir]]
  648. (when (contains? (:file/unlinked-dirs @state/state) dir)
  649. (notification/clear-all!)
  650. (state/pub-event! [:notification/show
  651. {:content (str "The directory " dir " has been back, you can edit your graph now.")
  652. :status :success
  653. :clear? true}])
  654. (state/update-state! :file/unlinked-dirs (fn [dirs] (disj dirs dir)))
  655. (when (= dir (config/get-repo-dir repo))
  656. (fs/watch-dir! dir))))
  657. (defmethod handle :ui/notify-files-with-reserved-chars [[_ paths]]
  658. (sync/<sync-stop)
  659. (notification/show!
  660. [:div
  661. [:div.mb-4
  662. [:div.font-semibold.mb-4.text-xl "It seems that some of your filenames are in the outdated format."]
  663. [:div
  664. [:p
  665. "We suggest you upgrade now to avoid some potential bugs."]
  666. [:p
  667. "For example, the files below have reserved characters can't be synced on some platforms."]]
  668. ]
  669. (ui/button
  670. "Update filename format"
  671. :on-click (fn []
  672. (notification/clear-all!)
  673. (state/set-modal!
  674. (fn [_] (conversion-component/files-breaking-changed))
  675. {:id :filename-format-panel :center? true})))
  676. [:ol.my-2
  677. (for [path paths]
  678. [:li path])]]
  679. :warning
  680. false))
  681. (defmethod handle :ui/notify-skipped-downloading-files [[_ paths]]
  682. (notification/show!
  683. [:div
  684. [:div.mb-4
  685. [:div.font-semibold.mb-4.text-xl "It seems that some of your filenames are in the outdated format."]
  686. [:p
  687. "The files below that have reserved characters can't be saved on this device."]
  688. [:div.overflow-y-auto.max-h-96
  689. [:ol.my-2
  690. (for [path paths]
  691. [:li path])]]
  692. [:div
  693. [:p
  694. "Check " [:a {:href "https://docs.logseq.com/#/page/logseq%20file%20and%20folder%20naming%20rules"
  695. :target "_blank"}
  696. "Logseq file and folder naming rules"]
  697. " for more details."]
  698. [:p
  699. "To solve this problem, we suggest you update the filename format (on Settings > Advanced > Filename format > click EDIT button) in other devices to avoid more potential bugs."]]]]
  700. :warning
  701. false))
  702. (defmethod handle :graph/setup-a-repo [[_ opts]]
  703. (let [opts' (merge {:picked-root-fn #(state/close-modal!)
  704. :native-icloud? (not (string/blank? (state/get-icloud-container-root-url)))
  705. :logged? (user-handler/logged-in?)} opts)]
  706. (if (mobile-util/native-ios?)
  707. (state/set-modal!
  708. #(graph-picker/graph-picker-cp opts')
  709. {:label "graph-setup"})
  710. (page-handler/ls-dir-files! st/refresh! opts'))))
  711. (defmethod handle :file/alter [[_ repo path content]]
  712. (p/let [_ (file-handler/alter-file repo path content {:from-disk? true})]
  713. (ui-handler/re-render-root!)))
  714. (rum/defcs file-id-conflict-item <
  715. (rum/local false ::resolved?)
  716. [state repo file data]
  717. (let [resolved? (::resolved? state)
  718. id (last (:assertion data))]
  719. [:li {:key file}
  720. [:div
  721. [:a {:on-click #(js/window.apis.openPath file)} file]
  722. (if @resolved?
  723. [:div.flex.flex-row.items-center
  724. (ui/icon "circle-check" {:style {:font-size 20}})
  725. [:div.ml-1 "Resolved"]]
  726. [:div
  727. [:p
  728. (str "It seems that another whiteboard file already has the ID \"" id
  729. "\". You can fix it by changing the ID in this file with another UUID.")]
  730. [:p
  731. "Or, let me"
  732. (ui/button "Fix"
  733. :on-click (fn []
  734. (let [dir (config/get-repo-dir repo)]
  735. (p/let [content (fs/read-file dir file)]
  736. (let [new-content (string/replace content (str id) (str (random-uuid)))]
  737. (p/let [_ (fs/write-file! repo
  738. dir
  739. file
  740. new-content
  741. {})]
  742. (reset! resolved? true))))))
  743. :class "inline mx-1")
  744. "it."]])]]))
  745. (defmethod handle :file/parse-and-load-error [[_ repo parse-errors]]
  746. (state/pub-event! [:notification/show
  747. {:content
  748. [:div
  749. [:h2.title "Oops. These files failed to import to your graph:"]
  750. [:ol.my-2
  751. (for [[file error] parse-errors]
  752. (let [data (ex-data error)]
  753. (cond
  754. (and (gp-config/whiteboard? file)
  755. (= :transact/upsert (:error data))
  756. (uuid? (last (:assertion data))))
  757. (rum/with-key (file-id-conflict-item repo file data) file)
  758. :else
  759. (do
  760. (state/pub-event! [:instrument {:type :file/parse-and-load-error
  761. :payload error}])
  762. [:li.my-1 {:key file}
  763. [:a {:on-click #(js/window.apis.openPath file)} file]
  764. [:p (.-message error)]]))))]
  765. [:p "Don't forget to re-index your graph when all the conflicts are resolved."]]
  766. :status :error}]))
  767. (defn run!
  768. []
  769. (let [chan (state/get-events-chan)]
  770. (async/go-loop []
  771. (let [payload (async/<! chan)]
  772. (try
  773. (handle payload)
  774. (catch :default error
  775. (let [type :handle-system-events/failed]
  776. (js/console.error (str type) (clj->js payload) "\n" error)
  777. (state/pub-event! [:instrument {:type type
  778. :payload payload
  779. :error error}])))))
  780. (recur))
  781. chan))
  782. (comment
  783. (let [{:keys [deprecated-app-id current-app-id]} {:deprecated-app-id "AFDADF9A-7466-4ED8-B74F-AAAA0D4565B9", :current-app-id "7563518E-0EFD-4AD2-8577-10CFFD6E4596"}]
  784. (def deprecated-app-id deprecated-app-id)
  785. (def current-app-id current-app-id))
  786. (def deprecated-repo (state/get-current-repo))
  787. (def new-repo (string/replace deprecated-repo deprecated-app-id current-app-id))
  788. (update-file-path deprecated-repo new-repo deprecated-app-id current-app-id)
  789. )