FsWatcher.swift 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. //
  2. // FsWatcher.swift
  3. // Logseq
  4. //
  5. // Created by Mono Wang on 2/17/R4.
  6. //
  7. import Foundation
  8. import Capacitor
  9. // MARK: Watcher Plugin
  10. @objc(FsWatcher)
  11. public class FsWatcher: CAPPlugin, PollingWatcherDelegate {
  12. private var watcher: PollingWatcher?
  13. private var baseUrl: URL?
  14. override public func load() {
  15. print("debug FsWatcher iOS plugin loaded!")
  16. }
  17. @objc func watch(_ call: CAPPluginCall) {
  18. if let path = call.getString("path") {
  19. guard let url = URL(string: path) else {
  20. call.reject("can not parse url")
  21. return
  22. }
  23. self.baseUrl = url
  24. self.watcher = PollingWatcher(at: url)
  25. self.watcher?.delegate = self
  26. self.watcher?.start()
  27. call.resolve(["ok": true])
  28. } else {
  29. call.reject("missing path string parameter")
  30. }
  31. }
  32. @objc func unwatch(_ call: CAPPluginCall) {
  33. watcher?.stop()
  34. watcher = nil
  35. baseUrl = nil
  36. call.resolve()
  37. }
  38. public func recevedNotification(_ url: URL, _ event: PollingWatcherEvent, _ metadata: SimpleFileMetadata?) {
  39. // NOTE: Event in js {dir path content stat{mtime}}
  40. switch event {
  41. case .Unlink:
  42. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  43. self.notifyListeners("watcher", data: ["event": "unlink",
  44. "dir": self.baseUrl?.description as Any,
  45. "path": url.description
  46. ])
  47. }
  48. case .Add, .Change:
  49. var content: String?
  50. if url.shouldNotifyWithContent() {
  51. content = try? String(contentsOf: url, encoding: .utf8)
  52. }
  53. self.notifyListeners("watcher", data: ["event": event.description,
  54. "dir": baseUrl?.description as Any,
  55. "path": url.description,
  56. "content": content as Any,
  57. "stat": ["mtime": metadata?.contentModificationTimestamp ?? 0,
  58. "ctime": metadata?.creationTimestamp ?? 0,
  59. "size": metadata?.fileSize as Any]
  60. ])
  61. case .Error:
  62. // TODO: handle error?
  63. break
  64. }
  65. }
  66. }
  67. // MARK: URL extension
  68. extension URL {
  69. func isSkipped() -> Bool {
  70. // skip hidden file
  71. if self.lastPathComponent.starts(with: ".") {
  72. return true
  73. }
  74. if self.absoluteString.contains("/logseq/bak/") || self.absoluteString.contains("/logseq/version-files/") {
  75. return true
  76. }
  77. if self.lastPathComponent == "graphs-txid.edn" || self.lastPathComponent == "broken-config.edn" {
  78. return true
  79. }
  80. return false
  81. }
  82. func shouldNotifyWithContent() -> Bool {
  83. let allowedPathExtensions: Set = ["md", "markdown", "org", "js", "edn", "css", "excalidraw"]
  84. if allowedPathExtensions.contains(self.pathExtension.lowercased()) {
  85. return true
  86. }
  87. return false
  88. }
  89. func isICloudPlaceholder() -> Bool {
  90. if self.lastPathComponent.starts(with: ".") && self.pathExtension.lowercased() == "icloud" {
  91. return true
  92. }
  93. return false
  94. }
  95. }
  96. // MARK: PollingWatcher
  97. public protocol PollingWatcherDelegate {
  98. func recevedNotification(_ url: URL, _ event: PollingWatcherEvent, _ metadata: SimpleFileMetadata?)
  99. }
  100. public enum PollingWatcherEvent {
  101. case Add
  102. case Change
  103. case Unlink
  104. case Error
  105. var description: String {
  106. switch self {
  107. case .Add:
  108. return "add"
  109. case .Change:
  110. return "change"
  111. case .Unlink:
  112. return "unlink"
  113. case .Error:
  114. return "error"
  115. }
  116. }
  117. }
  118. public struct SimpleFileMetadata: CustomStringConvertible, Equatable {
  119. var contentModificationTimestamp: Double
  120. var creationTimestamp: Double
  121. var fileSize: Int
  122. public init?(of fileURL: URL) {
  123. do {
  124. let fileAttributes = try fileURL.resourceValues(forKeys: [.isRegularFileKey, .fileSizeKey, .contentModificationDateKey, .creationDateKey])
  125. if fileAttributes.isRegularFile! {
  126. contentModificationTimestamp = fileAttributes.contentModificationDate?.timeIntervalSince1970 ?? 0.0
  127. creationTimestamp = fileAttributes.creationDate?.timeIntervalSince1970 ?? 0.0
  128. fileSize = fileAttributes.fileSize ?? 0
  129. } else {
  130. return nil
  131. }
  132. } catch {
  133. return nil
  134. }
  135. }
  136. public var description: String {
  137. return "Meta(size=\(self.fileSize), mtime=\(self.contentModificationTimestamp), ctime=\(self.creationTimestamp)"
  138. }
  139. }
  140. public class PollingWatcher {
  141. private let url: URL
  142. private var timer: DispatchSourceTimer?
  143. public var delegate: PollingWatcherDelegate?
  144. private var metaDb: [URL: SimpleFileMetadata] = [:]
  145. public init?(at: URL) {
  146. url = at
  147. }
  148. public func start() {
  149. self.tick(notify: false)
  150. let queue = DispatchQueue(label: Bundle.main.bundleIdentifier! + ".timer")
  151. timer = DispatchSource.makeTimerSource(queue: queue)
  152. timer!.setEventHandler(qos: .background, flags: []) { [weak self] in
  153. self?.tick(notify: true)
  154. }
  155. timer!.schedule(deadline: .now())
  156. timer!.resume()
  157. }
  158. deinit {
  159. self.stop()
  160. }
  161. public func stop() {
  162. timer?.cancel()
  163. timer = nil
  164. }
  165. private func tick(notify: Bool) {
  166. // let startTime = DispatchTime.now()
  167. if let enumerator = FileManager.default.enumerator(
  168. at: url,
  169. includingPropertiesForKeys: [.isRegularFileKey, .nameKey, .isDirectoryKey],
  170. // NOTE: icloud downloading requires non-skipsHiddenFiles
  171. options: [.skipsPackageDescendants]) {
  172. var newMetaDb: [URL: SimpleFileMetadata] = [:]
  173. for case let fileURL as URL in enumerator {
  174. guard let resourceValues = try? fileURL.resourceValues(forKeys: [.isRegularFileKey, .nameKey, .isDirectoryKey]),
  175. let isDirectory = resourceValues.isDirectory,
  176. let isRegularFile = resourceValues.isRegularFile,
  177. let name = resourceValues.name
  178. else {
  179. continue
  180. }
  181. if isDirectory {
  182. // NOTE: URL.path won't end with a `/`
  183. if fileURL.path.hasSuffix("/logseq/bak") || fileURL.path.hasSuffix("/logseq/version-files") || name == ".recycle" || name.hasPrefix(".") || name == "node_modules" {
  184. enumerator.skipDescendants()
  185. }
  186. }
  187. if isRegularFile && !fileURL.isSkipped() {
  188. if let meta = SimpleFileMetadata(of: fileURL) {
  189. newMetaDb[fileURL] = meta
  190. }
  191. } else if fileURL.isICloudPlaceholder() {
  192. try? FileManager.default.startDownloadingUbiquitousItem(at: fileURL)
  193. }
  194. }
  195. if notify {
  196. self.updateMetaDb(with: newMetaDb)
  197. } else {
  198. self.metaDb = newMetaDb
  199. }
  200. }
  201. // let elapsedNanoseconds = DispatchTime.now().uptimeNanoseconds - startTime.uptimeNanoseconds
  202. // let elapsedInMs = Double(elapsedNanoseconds) / 1_000_000
  203. // print("debug ticker elapsed=\(elapsedInMs)ms")
  204. if #available(iOS 13.0, *) {
  205. timer?.schedule(deadline: .now().advanced(by: .seconds(2)), leeway: .milliseconds(100))
  206. } else {
  207. // Fallback on earlier versions
  208. timer?.schedule(deadline: .now() + 2.0, leeway: .milliseconds(100))
  209. }
  210. }
  211. // TODO: batch?
  212. private func updateMetaDb(with newMetaDb: [URL: SimpleFileMetadata]) {
  213. for (url, meta) in newMetaDb {
  214. if let idx = self.metaDb.index(forKey: url) {
  215. let (_, oldMeta) = self.metaDb.remove(at: idx)
  216. if oldMeta != meta {
  217. self.delegate?.recevedNotification(url, .Change, meta)
  218. }
  219. } else {
  220. self.delegate?.recevedNotification(url, .Add, meta)
  221. }
  222. }
  223. for url in self.metaDb.keys {
  224. self.delegate?.recevedNotification(url, .Unlink, nil)
  225. }
  226. self.metaDb = newMetaDb
  227. }
  228. }