|
| 1 | +// |
| 2 | +// PluginDirectory.swift |
| 3 | +// BluetoothExplorerPluginEngine |
| 4 | +// |
| 5 | +// On-disk plugin storage under the app's Documents directory. |
| 6 | +// |
| 7 | +// Every plugin — bundled or user-imported — lives here, so there is one code path for loading and |
| 8 | +// one place a user can inspect. Bundled plugins are copied in on first launch and refreshed when a |
| 9 | +// new app build ships a different module; a bundled plugin the user deletes stays deleted, because |
| 10 | +// the install record remembers that it was already handled once. |
| 11 | +// |
| 12 | +// Layout: |
| 13 | +// Documents/Plugins/ |
| 14 | +// <plugin-id>/ |
| 15 | +// <name>.bleplugin.json |
| 16 | +// <name>.wasm |
| 17 | +// .installed-bundled.json |
| 18 | +// |
| 19 | + |
| 20 | +import Foundation |
| 21 | + |
| 22 | +public struct PluginDirectory: Sendable { |
| 23 | + |
| 24 | + /// Root of the plugin store, e.g. `Documents/Plugins`. |
| 25 | + public let url: URL |
| 26 | + |
| 27 | + private static let recordName = ".installed-bundled.json" |
| 28 | + |
| 29 | + public init(url: URL) { |
| 30 | + self.url = url |
| 31 | + } |
| 32 | + |
| 33 | + /// `Documents/Plugins`, created if absent. |
| 34 | + public static func `default`() throws -> PluginDirectory { |
| 35 | + let documents = try FileManager.default.url( |
| 36 | + for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true) |
| 37 | + let directory = PluginDirectory(url: documents.appendingPathComponent("Plugins", isDirectory: true)) |
| 38 | + try directory.createIfNeeded() |
| 39 | + return directory |
| 40 | + } |
| 41 | + |
| 42 | + public func createIfNeeded() throws { |
| 43 | + try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) |
| 44 | + } |
| 45 | + |
| 46 | + // MARK: Listing |
| 47 | + |
| 48 | + /// Manifest URLs for every installed plugin, one per plugin sub-directory. |
| 49 | + public func installedManifestURLs() -> [URL] { |
| 50 | + let contents = (try? FileManager.default.contentsOfDirectory( |
| 51 | + at: url, includingPropertiesForKeys: nil)) ?? [] |
| 52 | + var manifests = [URL]() |
| 53 | + for entry in contents.map({ $0 as URL }) { |
| 54 | + // `contentsOfDirectory` on a plain file throws, which is a portable directory test — |
| 55 | + // `ObjCBool` out-parameters are awkward outside Darwin's Foundation. |
| 56 | + guard let inner = try? FileManager.default.contentsOfDirectory( |
| 57 | + at: entry, includingPropertiesForKeys: nil) |
| 58 | + else { continue } |
| 59 | + for file in inner.map({ $0 as URL }) |
| 60 | + where file.lastPathComponent.hasSuffix(PluginDirectory.manifestSuffix) { |
| 61 | + manifests.append(file) |
| 62 | + } |
| 63 | + } |
| 64 | + return manifests.sorted { $0.path < $1.path } |
| 65 | + } |
| 66 | + |
| 67 | + public static let manifestSuffix = ".bleplugin.json" |
| 68 | + |
| 69 | + // MARK: Installing bundled plugins |
| 70 | + |
| 71 | + /// Copy bundled plugins into the store. |
| 72 | + /// |
| 73 | + /// A plugin is installed when it has never been installed before (first launch), or when the |
| 74 | + /// bundled module's hash differs from the one recorded (a new app build shipped an update). |
| 75 | + /// Plugins the user deleted are not resurrected. |
| 76 | + /// - Returns: the identifiers that were installed or refreshed. |
| 77 | + @discardableResult |
| 78 | + public func installBundledPlugins(from bundle: Bundle) throws -> [String] { |
| 79 | + try createIfNeeded() |
| 80 | + var record = installRecord() |
| 81 | + var installed = [String]() |
| 82 | + |
| 83 | + let discovered = bundle.urls(forResourcesWithExtension: "json", subdirectory: "Plugins") ?? [] |
| 84 | + for manifestURL in discovered.map({ $0 as URL }) |
| 85 | + where manifestURL.lastPathComponent.hasSuffix(PluginDirectory.manifestSuffix) { |
| 86 | + guard let data = try? Data(contentsOf: manifestURL), |
| 87 | + let manifest = try? JSONDecoder().decode(PluginManifest.self, from: data) |
| 88 | + else { continue } |
| 89 | + |
| 90 | + // The manifest's sha256 identifies this build of the module. Absent one, fall back to |
| 91 | + // the version string so a plugin without a hash still refreshes across releases. |
| 92 | + let stamp = manifest.sha256 ?? manifest.version |
| 93 | + if record[manifest.identifier] == stamp { continue } |
| 94 | + |
| 95 | + let moduleURL = manifestURL.deletingLastPathComponent() |
| 96 | + .appendingPathComponent(manifest.module) |
| 97 | + try install(manifestURL: manifestURL, moduleURL: moduleURL, identifier: manifest.identifier) |
| 98 | + record[manifest.identifier] = stamp |
| 99 | + installed.append(manifest.identifier) |
| 100 | + } |
| 101 | + |
| 102 | + try write(record: record) |
| 103 | + return installed |
| 104 | + } |
| 105 | + |
| 106 | + /// True when no bundled plugin has ever been installed — i.e. this is a first launch. |
| 107 | + public var isFirstLaunch: Bool { |
| 108 | + FileManager.default.fileExists(atPath: recordURL.path) == false |
| 109 | + } |
| 110 | + |
| 111 | + // MARK: Importing |
| 112 | + |
| 113 | + /// Import a plugin the user picked, copying its manifest and module into the store. |
| 114 | + /// |
| 115 | + /// `manifestURL` must be a `*.bleplugin.json`; the module named by the manifest is resolved |
| 116 | + /// alongside it. The plugin is validated before anything is written, so a bad import cannot |
| 117 | + /// leave a broken plugin on disk. |
| 118 | + @discardableResult |
| 119 | + public func importPlugin(manifestURL: URL) throws -> PluginManifest { |
| 120 | + try createIfNeeded() |
| 121 | + // Validate first: this parses the module, checks the ABI marker, capability exports and, |
| 122 | + // when the manifest carries a hash, verifies it. |
| 123 | + let loaded = try PluginLoader.load(manifestURL: manifestURL, verifyHash: true) |
| 124 | + let moduleURL = manifestURL.deletingLastPathComponent() |
| 125 | + .appendingPathComponent(loaded.manifest.module) |
| 126 | + try install(manifestURL: manifestURL, moduleURL: moduleURL, |
| 127 | + identifier: loaded.manifest.identifier) |
| 128 | + return loaded.manifest |
| 129 | + } |
| 130 | + |
| 131 | + /// Delete an installed plugin's directory. |
| 132 | + public func remove(identifier: String) throws { |
| 133 | + let directory = url.appendingPathComponent(Self.folderName(for: identifier), isDirectory: true) |
| 134 | + guard FileManager.default.fileExists(atPath: directory.path) else { return } |
| 135 | + try FileManager.default.removeItem(at: directory) |
| 136 | + } |
| 137 | + |
| 138 | + // MARK: Internals |
| 139 | + |
| 140 | + private func install(manifestURL: URL, moduleURL: URL, identifier: String) throws { |
| 141 | + let destination = url.appendingPathComponent(Self.folderName(for: identifier), isDirectory: true) |
| 142 | + if FileManager.default.fileExists(atPath: destination.path) { |
| 143 | + try FileManager.default.removeItem(at: destination) |
| 144 | + } |
| 145 | + try FileManager.default.createDirectory(at: destination, withIntermediateDirectories: true) |
| 146 | + |
| 147 | + let moduleData = try Data(contentsOf: moduleURL) |
| 148 | + let manifestData = try Data(contentsOf: manifestURL) |
| 149 | + try moduleData.write(to: destination.appendingPathComponent(moduleURL.lastPathComponent)) |
| 150 | + try manifestData.write(to: destination.appendingPathComponent(manifestURL.lastPathComponent)) |
| 151 | + } |
| 152 | + |
| 153 | + /// A filesystem-safe directory name for a reverse-DNS plugin identifier. |
| 154 | + public static func folderName(for identifier: String) -> String { |
| 155 | + var name = "" |
| 156 | + for character in identifier { |
| 157 | + if character.isLetter || character.isNumber || character == "." || character == "-" { |
| 158 | + name.append(character) |
| 159 | + } else { |
| 160 | + name.append("_") |
| 161 | + } |
| 162 | + } |
| 163 | + return name.isEmpty ? "plugin" : name |
| 164 | + } |
| 165 | + |
| 166 | + private var recordURL: URL { url.appendingPathComponent(PluginDirectory.recordName) } |
| 167 | + |
| 168 | + private func installRecord() -> [String: String] { |
| 169 | + guard let data = try? Data(contentsOf: recordURL), |
| 170 | + let record = try? JSONDecoder().decode([String: String].self, from: data) |
| 171 | + else { return [:] } |
| 172 | + return record |
| 173 | + } |
| 174 | + |
| 175 | + private func write(record: [String: String]) throws { |
| 176 | + let data = try JSONEncoder().encode(record) |
| 177 | + try data.write(to: recordURL) |
| 178 | + } |
| 179 | +} |
0 commit comments