Browse Source

fix(mobile): reload the app if db worker closed

Tienson Qin 2 months ago
parent
commit
43e7eda18d

+ 37 - 22
ios/App/App/AppDelegate.swift

@@ -1,34 +1,49 @@
-// AppDelegate.swift
 import UIKit
 import Capacitor
 
 @UIApplicationMain
 class AppDelegate: UIResponder, UIApplicationDelegate {
 
-  var window: UIWindow?
-  let maxBackgroundTime: TimeInterval = 300 // 5 minutes
+    var window: UIWindow?
 
-  func applicationDidEnterBackground(_ application: UIApplication) {
-    UserDefaults.standard.set(Date(), forKey: "backgroundEnterDate")
-  }
+    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
+        // Override point for customization after application launch.
 
-  func applicationWillEnterForeground(_ application: UIApplication) {
-    if let backgroundDate = UserDefaults.standard.object(forKey: "backgroundEnterDate") as? Date {
-      let elapsed = Date().timeIntervalSince(backgroundDate)
-      if elapsed > maxBackgroundTime {
-          requestJsReload()
-      }
+        return true
     }
-    UserDefaults.standard.removeObject(forKey: "backgroundEnterDate")
-  }
 
-  private func requestJsReload() {
-      // Find the Bridge VC to get the bridge
-      guard let root = window?.rootViewController else { return }
-      let bridgeVC =
-        (root as? UINavigationController)?.viewControllers.first as? CAPBridgeViewController
-        ?? (root as? CAPBridgeViewController)
+    func applicationWillResignActive(_ application: UIApplication) {
+        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
+        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
+    }
+
+    func applicationDidEnterBackground(_ application: UIApplication) {
+        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
+        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
+    }
+
+    func applicationWillEnterForeground(_ application: UIApplication) {
+        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
+    }
+
+    func applicationDidBecomeActive(_ application: UIApplication) {
+        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
+
+    }
+
+    func applicationWillTerminate(_ application: UIApplication) {
+        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
+    }
+
+    func application(_ application: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
+        return ApplicationDelegateProxy.shared.application(application, open: url, options: options)
+    }
+
+    func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
+        // Called when the app was launched with an activity, including Universal Links.
+        // Feel free to add additional processing here, but if you want the App API to support
+        // tracking app url opens, make sure to keep this call
+        return ApplicationDelegateProxy.shared.application(application, continue: userActivity, restorationHandler: restorationHandler)
+    }
 
-      bridgeVC?.bridge?.triggerJSEvent(eventName: "AppRestartRequired", target: "window")
-  }
 }

+ 4 - 0
src/main/frontend/handler/worker.cljs

@@ -49,6 +49,10 @@
 (defmethod handle :export-current-db [_]
   (state/pub-event! [:db/export-sqlite]))
 
+(defmethod handle :record-worker-client-id [_ _worker data]
+  (when-let [client-id (:client-id data)]
+    (reset! state/*db-worker-client-id client-id)))
+
 (defmethod handle :capture-error [_ _worker data]
   (state/pub-event! [:capture-error data]))
 

+ 2 - 2
src/main/frontend/persist_db/browser.cljs

@@ -108,8 +108,8 @@
       (Comlink/expose #js{"remoteInvoke" thread-api/remote-function} worker)
       (worker-handler/handle-message! worker wrapped-worker)
       (reset! state/*db-worker wrapped-worker)
-      (-> (p/let [_ (sync-app-state!)
-                  _ (state/<invoke-db-worker :thread-api/init config/RTC-WS-URL)
+      (-> (p/let [_ (state/<invoke-db-worker :thread-api/init config/RTC-WS-URL)
+                  _ (sync-app-state!)
                   _ (js/console.debug (str "debug: init worker spent: " (- (util/time-ms) t1) "ms"))
                   _ (sync-ui-state!)
                   _ (ask-persist-permission!)

+ 1 - 0
src/main/frontend/state.cljs

@@ -33,6 +33,7 @@
 (defonce *profile-state (volatile! {}))
 
 (defonce *db-worker (atom nil))
+(defonce *db-worker-client-id (atom nil))
 (defonce *editor-info (atom nil))
 
 (def db-worker-ready-flow

+ 4 - 1
src/main/frontend/worker/db_worker.cljs

@@ -864,7 +864,10 @@
                                 ;; because shared-service operates at the graph level,
                                 ;; creating a new database or switching to another one requires re-initializing the service.
                                 (let [[graph opts] (ldb/read-transit-str (last args))]
-                                  (p/let [service (<init-service! graph opts)]
+                                  (p/let [service (<init-service! graph opts)
+                                          client-id (:client-id service)]
+                                    (when client-id
+                                      (worker-util/post-message :record-worker-client-id {:client-id client-id}))
                                     (get-in service [:status :ready])
                                     ;; wait for service ready
                                     (js-invoke (:proxy service) k args)))

+ 2 - 1
src/main/frontend/worker/shared_service.cljs

@@ -353,7 +353,8 @@
                                                                              :method method
                                                                              :args args})))))))
                                      (log/error :invalid-invoke-method method)))})
-     :status status}))
+     :status status
+     :client-id client-id}))
 
 (defn broadcast-to-clients!
   [type' data]

+ 0 - 9
src/main/mobile/core.cljs

@@ -73,21 +73,12 @@
    ;; set to false to enable HistoryAPI
    {:use-fragment true}))
 
-(defn listen-to-reload-app
-  []
-  (.addEventListener js/window "AppRestartRequired"
-                     (fn []
-                       (prn :debug :app-restarted)
-                       (.reload js/window.location))))
-
 (defn ^:export init []
   ;; init is called ONCE when the page loads
   ;; this is called in the index.html and must be exported
   ;; so it is available even in :advanced release builds
   (prn "[Mobile] init!")
 
-  (listen-to-reload-app)
-
   (set-router!)
   (init/init!)
   (fhandler/start! render!))

+ 11 - 2
src/main/mobile/init.cljs

@@ -74,8 +74,17 @@
   (reset! mobile-flows/*mobile-app-state (.-isActive state))
   (when (state/get-current-repo)
     (let [is-active? (.-isActive state)]
-      (when-not is-active?
-        (editor-handler/save-current-block!)))))
+      (if (not is-active?)
+        (editor-handler/save-current-block!)
+        ;; check whether db-worker is available
+        (when-let [client-id @state/*db-worker-client-id]
+          (when @state/*db-worker
+            (js/navigator.locks.request client-id #js {:mode "exclusive"
+                                                       :ifAvailable true}
+                                        (fn [lock]
+                                          (when lock
+                                            ;; lock acquired, meaning the worker has terminated
+                                            (js/window.location.reload))))))))))
 
 (defn- general-init
   "Initialize event listeners used by both iOS and Android"