@blotch/angular-lynx-native 22.3.1 → 22.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (123) hide show
  1. package/README.md +47 -15
  2. package/dist/android/project.d.ts +114 -1
  3. package/dist/android/project.d.ts.map +1 -1
  4. package/dist/android/project.js +440 -5
  5. package/dist/eject.d.ts +15 -1
  6. package/dist/eject.d.ts.map +1 -1
  7. package/dist/eject.js +14 -2
  8. package/dist/features.d.ts +70 -0
  9. package/dist/features.d.ts.map +1 -0
  10. package/dist/features.js +115 -0
  11. package/dist/files.d.ts +24 -0
  12. package/dist/files.d.ts.map +1 -0
  13. package/dist/files.js +41 -0
  14. package/dist/generate.d.ts +34 -3
  15. package/dist/generate.d.ts.map +1 -1
  16. package/dist/generate.js +78 -19
  17. package/dist/index.d.ts +1 -0
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +16 -2
  20. package/dist/ios/build.d.ts.map +1 -1
  21. package/dist/ios/build.js +8 -2
  22. package/dist/ios/frameworks.d.ts +6 -5
  23. package/dist/ios/frameworks.d.ts.map +1 -1
  24. package/dist/ios/frameworks.js +46 -15
  25. package/dist/ios/project.d.ts +192 -11
  26. package/dist/ios/project.d.ts.map +1 -1
  27. package/dist/ios/project.js +823 -33
  28. package/dist/options.d.ts +208 -1
  29. package/dist/options.d.ts.map +1 -1
  30. package/dist/options.js +154 -0
  31. package/dist/permissions.d.ts +18 -1
  32. package/dist/permissions.d.ts.map +1 -1
  33. package/dist/permissions.js +79 -4
  34. package/dist/plugins.d.ts +245 -0
  35. package/dist/plugins.d.ts.map +1 -0
  36. package/dist/plugins.js +1244 -0
  37. package/package.json +1 -1
  38. package/templates/android/README.md +46 -5
  39. package/templates/android/angular-lynx.properties +2 -0
  40. package/templates/android/app/build.gradle.kts +78 -11
  41. package/templates/android/app/src/main/AndroidManifest.xml +19 -3
  42. package/templates/android/app/src/main/java/dev/angularlynx/shell/AngularLynxPlugins.kt +13 -0
  43. package/templates/android/app/src/main/java/dev/angularlynx/shell/AudioRecorderModule.kt +520 -0
  44. package/templates/android/app/src/main/java/dev/angularlynx/shell/BarcodeScannerModule.kt +144 -0
  45. package/templates/android/app/src/main/java/dev/angularlynx/shell/BiometricsModule.kt +433 -0
  46. package/templates/android/app/src/main/java/dev/angularlynx/shell/BitmapPresenter.kt +98 -0
  47. package/templates/android/app/src/main/java/dev/angularlynx/shell/BitmapRendererContext.kt +175 -0
  48. package/templates/android/app/src/main/java/dev/angularlynx/shell/BluetoothModule.kt +1288 -0
  49. package/templates/android/app/src/main/java/dev/angularlynx/shell/CalendarModule.kt +127 -0
  50. package/templates/android/app/src/main/java/dev/angularlynx/shell/Canvas2DContext.kt +1557 -0
  51. package/templates/android/app/src/main/java/dev/angularlynx/shell/Canvas2DOps.kt +63 -0
  52. package/templates/android/app/src/main/java/dev/angularlynx/shell/CanvasFilter.kt +357 -0
  53. package/templates/android/app/src/main/java/dev/angularlynx/shell/CanvasUI.kt +4 -3
  54. package/templates/android/app/src/main/java/dev/angularlynx/shell/EdgeToEdgeOverlay.kt +24 -0
  55. package/templates/android/app/src/main/java/dev/angularlynx/shell/EngineThreadHint.kt +156 -0
  56. package/templates/android/app/src/main/java/dev/angularlynx/shell/FilePickerModule.kt +263 -0
  57. package/templates/android/app/src/main/java/dev/angularlynx/shell/GeolocationModule.kt +557 -0
  58. package/templates/android/app/src/main/java/dev/angularlynx/shell/HapticsModule.kt +82 -0
  59. package/templates/android/app/src/main/java/dev/angularlynx/shell/HostElementUI.kt +331 -0
  60. package/templates/android/app/src/main/java/dev/angularlynx/shell/ImagePickerModule.kt +143 -0
  61. package/templates/android/app/src/main/java/dev/angularlynx/shell/ImagePipeline.kt +83 -0
  62. package/templates/android/app/src/main/java/dev/angularlynx/shell/MainActivity.kt +523 -9
  63. package/templates/android/app/src/main/java/dev/angularlynx/shell/ModuleBytes.kt +58 -0
  64. package/templates/android/app/src/main/java/dev/angularlynx/shell/MotionModule.kt +332 -0
  65. package/templates/android/app/src/main/java/dev/angularlynx/shell/NetworkStatus.kt +121 -0
  66. package/templates/android/app/src/main/java/dev/angularlynx/shell/NfcModule.kt +274 -0
  67. package/templates/android/app/src/main/java/dev/angularlynx/shell/PermissionRequests.kt +35 -0
  68. package/templates/android/app/src/main/java/dev/angularlynx/shell/PhotoLibraryModule.kt +355 -0
  69. package/templates/android/app/src/main/java/dev/angularlynx/shell/ShareTargetModule.kt +234 -0
  70. package/templates/android/app/src/main/java/dev/angularlynx/shell/ShellApplication.kt +7 -8
  71. package/templates/android/app/src/main/java/dev/angularlynx/shell/ShellModule.kt +58 -4
  72. package/templates/android/app/src/main/java/dev/angularlynx/shell/StoreReviewModule.kt +66 -0
  73. package/templates/android/app/src/main/java/dev/angularlynx/shell/SystemFontFamilies.kt +68 -0
  74. package/templates/android/app/src/main/java/dev/angularlynx/shell/TrackingModule.kt +74 -0
  75. package/templates/android/app/src/main/java/dev/angularlynx/shell/VideoFrameTarget.kt +429 -0
  76. package/templates/android/app/src/main/java/dev/angularlynx/shell/VideoUI.kt +676 -0
  77. package/templates/android/app/src/main/java/dev/angularlynx/shell/WebGLContext.kt +128 -13
  78. package/templates/android/app/src/main/java/dev/angularlynx/shell/WebGLModule.kt +493 -65
  79. package/templates/android/app/src/main/java/dev/angularlynx/shell/WifiModule.kt +429 -0
  80. package/templates/android/app/src/main/res/values/biometrics.xml +9 -0
  81. package/templates/android/app/src/main/res/values/share_target.xml +11 -0
  82. package/templates/android/app/src/main/res/xml/backup_rules.xml +5 -3
  83. package/templates/android/app/src/main/res/xml/data_extraction_rules.xml +6 -3
  84. package/templates/android/app/src/main/res/xml/share_paths.xml +7 -2
  85. package/templates/android/build.gradle.kts +1 -1
  86. package/templates/android/gradle/wrapper/gradle-wrapper.properties +2 -2
  87. package/templates/ios/App/AngularLynxBitmapRendererContext.m +188 -0
  88. package/templates/ios/App/AngularLynxCanvas2DContext.m +2467 -0
  89. package/templates/ios/App/AngularLynxCanvas2DOps.h +61 -0
  90. package/templates/ios/App/AngularLynxPlugins.swift +22 -0
  91. package/templates/ios/App/AngularLynxVideo.h +37 -0
  92. package/templates/ios/App/AngularLynxVideo.m +435 -0
  93. package/templates/ios/App/AngularLynxWebGL.h +69 -7
  94. package/templates/ios/App/AngularLynxWebGL.m +538 -29
  95. package/templates/ios/App/AngularLynxWebGLContext.m +148 -46
  96. package/templates/ios/App/AnimationFrameRate.swift +66 -0
  97. package/templates/ios/App/AppDelegate.swift +37 -3
  98. package/templates/ios/App/AppleSignInButton.swift +106 -0
  99. package/templates/ios/App/AppleSignInModule.swift +222 -0
  100. package/templates/ios/App/AudioRecorderModule.swift +433 -0
  101. package/templates/ios/App/BarcodeScannerModule.swift +284 -0
  102. package/templates/ios/App/BiometricsModule.swift +256 -0
  103. package/templates/ios/App/BluetoothModule.swift +1086 -0
  104. package/templates/ios/App/CalendarModule.swift +158 -0
  105. package/templates/ios/App/FilePickerModule.swift +240 -0
  106. package/templates/ios/App/GeolocationModule.swift +455 -0
  107. package/templates/ios/App/HapticsModule.swift +90 -0
  108. package/templates/ios/App/HostElementUI.swift +270 -0
  109. package/templates/ios/App/ImagePickerModule.swift +160 -1
  110. package/templates/ios/App/Info.plist +2 -0
  111. package/templates/ios/App/LynxViewController.swift +274 -9
  112. package/templates/ios/App/MotionModule.swift +430 -0
  113. package/templates/ios/App/NetworkStatus.swift +41 -0
  114. package/templates/ios/App/NfcModule.swift +346 -0
  115. package/templates/ios/App/PhotoLibraryModule.swift +169 -0
  116. package/templates/ios/App/ShareTargetModule.swift +150 -0
  117. package/templates/ios/App/ShellModule.swift +17 -0
  118. package/templates/ios/App/StoreReviewModule.swift +61 -0
  119. package/templates/ios/App/TrackingModule.swift +121 -0
  120. package/templates/ios/App/WifiModule.swift +237 -0
  121. package/templates/ios/App/XElementRegistry.swift +13 -3
  122. package/templates/ios/ShareExtension/Info.plist +42 -0
  123. package/templates/ios/ShareExtension/ShareViewController.swift +387 -0
@@ -0,0 +1,222 @@
1
+ import AuthenticationServices
2
+ import Lynx
3
+ import UIKit
4
+
5
+ /// The native module behind the runtime's `LynxAppleSignIn`, which calls it as
6
+ /// `NativeModules.AngularLynxAppleSignIn` (from the background thread, where
7
+ /// NativeModules lives).
8
+ ///
9
+ /// `signIn` opens Sign in with Apple's own sheet
10
+ /// (`ASAuthorizationAppleIDProvider`) over the app's key window, the usual
11
+ /// way to meet App Review's guideline 4.8 beside other social logins, and
12
+ /// calls back once with the credential: the stable user identifier, the identity token
13
+ /// and the authorization code the app's server checks with Apple, and the
14
+ /// email and name, which Apple gives only on the person's first sign-in.
15
+ /// `credentialState` asks Apple whether a user identifier is still signed in,
16
+ /// which Apple asks apps to check at launch, `available` says the module
17
+ /// is there, and `button` that `<apple-sign-in-button>` is (AppleSignInButton).
18
+ ///
19
+ /// The sheet needs the `com.apple.developer.applesignin` entitlement, which a
20
+ /// free Personal Team can't sign, so the generator writes it and keeps this
21
+ /// file only in an app whose angular.json sets `signInWithApple`.
22
+ /// LynxViewController registers the module by its Objective-C name only when
23
+ /// it's there, hence the `@objc` name.
24
+ @objc(AngularLynxAppleSignInModule)
25
+ final class AppleSignInModule: NSObject, LynxModule, ASAuthorizationControllerDelegate,
26
+ ASAuthorizationControllerPresentationContextProviding
27
+ {
28
+ static var name: String { "AngularLynxAppleSignIn" }
29
+
30
+ static var methodLookup: [String: String] {
31
+ [
32
+ "available": NSStringFromSelector(#selector(available(_:))),
33
+ "signIn": NSStringFromSelector(#selector(signIn(_:callback:))),
34
+ "credentialState": NSStringFromSelector(#selector(credentialState(_:callback:))),
35
+ "button": NSStringFromSelector(#selector(button)),
36
+ ]
37
+ }
38
+
39
+ /// The open sign-in and its callback. Held until it ends: the controller's
40
+ /// delegate is weak, and a released controller never calls back.
41
+ private var controller: ASAuthorizationController?
42
+ private var callback: LynxCallbackBlock?
43
+
44
+ override init() {
45
+ super.init()
46
+ }
47
+
48
+ // Swift can't import an optional initializer as optional, so Lynx's
49
+ // initWithParam: is required here. Registered without a param, the module
50
+ // ignores it.
51
+ init(param: Any) {
52
+ super.init()
53
+ }
54
+
55
+ /// Calls back `{ available: true }`: the shell supports iOS 15 and later,
56
+ /// all of which have the sheet, so an app with the module can always open
57
+ /// it. Without the module, the runtime's call fails, which it reads as
58
+ /// unavailable.
59
+ @objc func available(_ callback: @escaping LynxCallbackBlock) {
60
+ callback(["available": true])
61
+ }
62
+
63
+ /// Returns `{ available: true }`: the shell registers `<apple-sign-in-button>`
64
+ /// (AppleSignInButton) with this module. The runtime calls it from the main
65
+ /// thread, where Angular makes elements, to choose between iOS's button and
66
+ /// the one it draws itself; without the module it gets no answer.
67
+ @objc func button() -> [String: Any] {
68
+ ["available": true]
69
+ }
70
+
71
+ /// Opens the sheet with `request`'s `scopes` (`email`, `fullName`), `nonce`
72
+ /// and `state`, and calls back once with the credential, or with
73
+ /// `{ error, message }`, where `error` is `canceled` or `failed`.
74
+ @objc func signIn(_ request: [String: Any], callback: @escaping LynxCallbackBlock) {
75
+ // Lynx calls modules off the main thread, and the sheet is UI.
76
+ DispatchQueue.main.async {
77
+ self.open(request, callback)
78
+ }
79
+ }
80
+
81
+ private func open(_ request: [String: Any], _ callback: @escaping LynxCallbackBlock) {
82
+ guard controller == nil else {
83
+ callback(["error": "failed", "message": "A sign-in is already open."])
84
+ return
85
+ }
86
+ let appleIDRequest = ASAuthorizationAppleIDProvider().createRequest()
87
+ let scopes = request["scopes"] as? [String] ?? []
88
+ appleIDRequest.requestedScopes = scopes.compactMap { scope in
89
+ switch scope {
90
+ case "email": return .email
91
+ case "fullName": return .fullName
92
+ default: return nil
93
+ }
94
+ }
95
+ if let nonce = request["nonce"] as? String {
96
+ appleIDRequest.nonce = nonce
97
+ }
98
+ if let state = request["state"] as? String {
99
+ appleIDRequest.state = state
100
+ }
101
+ let controller = ASAuthorizationController(authorizationRequests: [appleIDRequest])
102
+ controller.delegate = self
103
+ controller.presentationContextProvider = self
104
+ self.controller = controller
105
+ self.callback = callback
106
+ controller.performRequests()
107
+ }
108
+
109
+ /// Calls back the open sign-in's callback once, and lets the next one open.
110
+ private func finish(_ result: [String: Any]) {
111
+ let callback = self.callback
112
+ controller = nil
113
+ self.callback = nil
114
+ callback?(result)
115
+ }
116
+
117
+ func authorizationController(
118
+ controller: ASAuthorizationController,
119
+ didCompleteWithAuthorization authorization: ASAuthorization
120
+ ) {
121
+ guard let credential = authorization.credential as? ASAuthorizationAppleIDCredential else {
122
+ finish(["error": "failed", "message": "Apple gave no Apple ID credential."])
123
+ return
124
+ }
125
+ var result: [String: Any] = [
126
+ "user": credential.user,
127
+ "realUserStatus": Self.statusName(credential.realUserStatus),
128
+ ]
129
+ // Both are UTF-8 text: the token a JWT, the code a short string. They're
130
+ // missing only when Apple couldn't make them, which the runtime reports.
131
+ if let token = credential.identityToken.flatMap({ String(data: $0, encoding: .utf8) }) {
132
+ result["identityToken"] = token
133
+ }
134
+ if let code = credential.authorizationCode.flatMap({ String(data: $0, encoding: .utf8) }) {
135
+ result["authorizationCode"] = code
136
+ }
137
+ if let email = credential.email {
138
+ result["email"] = email
139
+ }
140
+ if let state = credential.state {
141
+ result["state"] = state
142
+ }
143
+ // Only on the first sign-in with the fullName scope, and then with only
144
+ // the parts the person filled in.
145
+ if let name = credential.fullName {
146
+ let parts: [String: String?] = [
147
+ "givenName": name.givenName,
148
+ "familyName": name.familyName,
149
+ "middleName": name.middleName,
150
+ "nickname": name.nickname,
151
+ "namePrefix": name.namePrefix,
152
+ "nameSuffix": name.nameSuffix,
153
+ ]
154
+ let given = parts.compactMapValues { $0 }
155
+ if !given.isEmpty {
156
+ result["fullName"] = given
157
+ }
158
+ }
159
+ finish(result)
160
+ }
161
+
162
+ func authorizationController(
163
+ controller: ASAuthorizationController,
164
+ didCompleteWithError error: Error
165
+ ) {
166
+ // The person closed the sheet.
167
+ if let error = error as? ASAuthorizationError, error.code == .canceled {
168
+ finish(["error": "canceled", "message": "The sign-in was canceled."])
169
+ return
170
+ }
171
+ // Code 1000 (unknown) covers more than one cause: a phone with no Apple
172
+ // Account, where iOS offers Settings and closing that alert ends the
173
+ // request (AuthKit's -7022 underneath, seen on the Simulator), and an
174
+ // app signed without the entitlement. The code goes in the message so
175
+ // the app's logs can tell them apart from the others.
176
+ finish([
177
+ "error": "failed",
178
+ "message": "Sign in with Apple failed: \(error.localizedDescription) (\((error as NSError).code))",
179
+ ])
180
+ }
181
+
182
+ /// The sheet opens over the app's window.
183
+ func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
184
+ UIApplication.shared.connectedScenes
185
+ .compactMap { $0 as? UIWindowScene }
186
+ .flatMap(\.windows)
187
+ .first(where: \.isKeyWindow) ?? ASPresentationAnchor()
188
+ }
189
+
190
+ /// Calls back `{ state }` for `user`, an identifier a sign-in returned:
191
+ /// `authorized`, `revoked` (the person stopped using Apple ID with the app),
192
+ /// `notFound` or `transferred` (the app moved to another team), or
193
+ /// `{ error, message }`.
194
+ @objc func credentialState(_ user: String, callback: @escaping LynxCallbackBlock) {
195
+ ASAuthorizationAppleIDProvider().getCredentialState(forUserID: user) { state, error in
196
+ if let error {
197
+ callback(["error": "failed", "message": error.localizedDescription])
198
+ return
199
+ }
200
+ callback(["state": Self.stateName(state)])
201
+ }
202
+ }
203
+
204
+ private static func stateName(_ state: ASAuthorizationAppleIDProvider.CredentialState) -> String {
205
+ switch state {
206
+ case .authorized: return "authorized"
207
+ case .revoked: return "revoked"
208
+ case .notFound: return "notFound"
209
+ case .transferred: return "transferred"
210
+ @unknown default: return "notFound"
211
+ }
212
+ }
213
+
214
+ private static func statusName(_ status: ASUserDetectionStatus) -> String {
215
+ switch status {
216
+ case .likelyReal: return "likelyReal"
217
+ case .unknown: return "unknown"
218
+ case .unsupported: return "unsupported"
219
+ @unknown default: return "unknown"
220
+ }
221
+ }
222
+ }
@@ -0,0 +1,433 @@
1
+ import AVFoundation
2
+ import Foundation
3
+ import Lynx
4
+ import UIKit
5
+
6
+ /// The native module behind the runtime's `LynxAudioRecorder`, which calls it
7
+ /// as `NativeModules.AngularLynxAudioRecorder` (from the background thread,
8
+ /// where NativeModules lives). Android's shell has one of the same name.
9
+ ///
10
+ /// It records AAC into an `.m4a` file in the app's temporary folder with
11
+ /// `AVAudioRecorder`, one recording at a time:
12
+ ///
13
+ /// - `permission` calls back `{ permission }`: `granted`, `denied` or
14
+ /// `undetermined`, without asking.
15
+ /// - `requestPermission` asks, if the person hasn't been asked, and calls back
16
+ /// `{ permission }` once they answer.
17
+ /// - `start` takes `{ recording, maxDuration? }`, asks first if it needs to,
18
+ /// and calls back `{}` once it records, or `{ error, message }`: `denied`,
19
+ /// `busy` while another recording is open, or `failed`.
20
+ /// - `pause` and `resume` call back `{}`.
21
+ /// - `stop` ends the recording and calls back `{ clip }`: `{ uri, name,
22
+ /// durationMs, mimeType, size }`. Once it ended by itself, it calls back
23
+ /// with that clip.
24
+ /// - `cancel` ends it and deletes the file.
25
+ /// - `read` takes `{ uri }` and calls back `{ base64 }`, the bytes of a clip
26
+ /// this module recorded.
27
+ ///
28
+ /// What the app didn't ask for at that moment arrives as the
29
+ /// `angularLynxAudioRecorder` global event, carrying the `recording` id
30
+ /// `start` was given: `level` about ten times a second while it records
31
+ /// (`{ level, durationMs }`), `paused` when the system paused it (a phone
32
+ /// call, Siri, or the app going to the background, since it records in the
33
+ /// foreground only), and `ended` once it reached `maxDuration` (`{ clip }`)
34
+ /// or failed (`{ error, message }`).
35
+ ///
36
+ /// App Store Connect flags an app whose code uses the microphone without
37
+ /// `NSMicrophoneUsageDescription` (ITMS-90683), which the generator writes
38
+ /// only for an app whose angular.json sets `permissions.microphone`, so it
39
+ /// keeps this file only then, and LynxViewController registers the class by
40
+ /// its Objective-C name instead of naming it.
41
+ ///
42
+ /// Everything here, the methods Lynx calls on its JavaScript thread, the
43
+ /// meter's timer and the session's notifications, runs on `queue`, so the
44
+ /// state needs no lock.
45
+ @objc(AngularLynxAudioRecorderModule)
46
+ final class AudioRecorderModule: NSObject, LynxContextModule, AVAudioRecorderDelegate {
47
+ static var name: String { "AngularLynxAudioRecorder" }
48
+
49
+ static let eventName = "angularLynxAudioRecorder"
50
+
51
+ static var methodLookup: [String: String] {
52
+ [
53
+ "permission": NSStringFromSelector(#selector(permission(_:))),
54
+ "requestPermission": NSStringFromSelector(#selector(requestPermission(_:))),
55
+ "start": NSStringFromSelector(#selector(start(_:callback:))),
56
+ "pause": NSStringFromSelector(#selector(pause(_:))),
57
+ "resume": NSStringFromSelector(#selector(resume(_:))),
58
+ "stop": NSStringFromSelector(#selector(stop(_:))),
59
+ "cancel": NSStringFromSelector(#selector(cancel(_:))),
60
+ "read": NSStringFromSelector(#selector(read(_:callback:))),
61
+ ]
62
+ }
63
+
64
+ /// How often the meter is read and sent, in seconds.
65
+ private static let levelInterval = 0.1
66
+ /// The quietest level a meter shows, in dBFS: the runtime's 0.
67
+ private static let levelFloor: Float = -60
68
+
69
+ private weak var context: LynxContext?
70
+ private let queue = DispatchQueue(label: "dev.angularlynx.audio-recorder")
71
+ private lazy var notifications: OperationQueue = {
72
+ let operations = OperationQueue()
73
+ operations.underlyingQueue = queue
74
+ operations.maxConcurrentOperationCount = 1
75
+ return operations
76
+ }()
77
+ private var observers: [NSObjectProtocol] = []
78
+
79
+ private struct Recording {
80
+ let id: Int
81
+ let recorder: AVAudioRecorder
82
+ let url: URL
83
+ let maxDuration: TimeInterval?
84
+ /// How long it recorded before its latest start or resume.
85
+ var recorded: TimeInterval = 0
86
+ /// When it last started or resumed, by the system's uptime (which the
87
+ /// clock being set can't move), or nil while it's paused.
88
+ var since: TimeInterval? = ProcessInfo.processInfo.systemUptime
89
+ /// What the audio session was before this recording, which it puts back.
90
+ let previous: (AVAudioSession.Category, AVAudioSession.Mode, AVAudioSession.CategoryOptions)
91
+
92
+ var elapsed: TimeInterval {
93
+ recorded + (since.map { ProcessInfo.processInfo.systemUptime - $0 } ?? 0)
94
+ }
95
+ }
96
+
97
+ private var recording: Recording?
98
+ /// The clip of the recording that ended by itself, for the `stop` after it.
99
+ private var ended: [String: Any]?
100
+ private var timer: DispatchSourceTimer?
101
+
102
+ override init() {
103
+ super.init()
104
+ }
105
+
106
+ // Swift can't import an optional initializer as optional, so Lynx's
107
+ // initWithParam: and initWithLynxContext:WithParam: are required here.
108
+ init(param: Any) {
109
+ super.init()
110
+ }
111
+
112
+ init(lynxContext context: LynxContext) {
113
+ self.context = context
114
+ super.init()
115
+ }
116
+
117
+ init(lynxContext context: LynxContext, withParam param: Any) {
118
+ self.context = context
119
+ super.init()
120
+ }
121
+
122
+ deinit {
123
+ for observer in observers { NotificationCenter.default.removeObserver(observer) }
124
+ timer?.cancel()
125
+ // The page closed mid-recording: nobody can have the clip, and the next
126
+ // page shouldn't inherit the recording's session.
127
+ if let current = recording {
128
+ current.recorder.stop()
129
+ current.recorder.deleteRecording()
130
+ restore(current.previous)
131
+ }
132
+ }
133
+
134
+ // MARK: - Permission
135
+
136
+ @objc func permission(_ callback: @escaping LynxCallbackBlock) {
137
+ callback(["permission": Self.currentPermission()])
138
+ }
139
+
140
+ @objc func requestPermission(_ callback: @escaping LynxCallbackBlock) {
141
+ Self.ask { _ in callback(["permission": Self.currentPermission()]) }
142
+ }
143
+
144
+ private static func currentPermission() -> String {
145
+ if #available(iOS 17.0, *) {
146
+ switch AVAudioApplication.shared.recordPermission {
147
+ case .granted: return "granted"
148
+ case .denied: return "denied"
149
+ default: return "undetermined"
150
+ }
151
+ }
152
+ switch AVAudioSession.sharedInstance().recordPermission {
153
+ case .granted: return "granted"
154
+ case .denied: return "denied"
155
+ default: return "undetermined"
156
+ }
157
+ }
158
+
159
+ /// Shows iOS's microphone prompt, with the app's
160
+ /// NSMicrophoneUsageDescription, unless the person has answered it before.
161
+ private static func ask(_ done: @escaping (Bool) -> Void) {
162
+ if #available(iOS 17.0, *) {
163
+ AVAudioApplication.requestRecordPermission(completionHandler: done)
164
+ } else {
165
+ AVAudioSession.sharedInstance().requestRecordPermission(done)
166
+ }
167
+ }
168
+
169
+ // MARK: - Recording
170
+
171
+ @objc func start(_ options: [String: Any], callback: @escaping LynxCallbackBlock) {
172
+ Self.ask { [weak self] granted in
173
+ guard let self else { return }
174
+ self.queue.async {
175
+ guard granted else {
176
+ callback(Self.failure("denied", "The person didn't allow the microphone."))
177
+ return
178
+ }
179
+ callback(self.begin(options))
180
+ }
181
+ }
182
+ }
183
+
184
+ private func begin(_ options: [String: Any]) -> [String: Any] {
185
+ if recording != nil {
186
+ return Self.failure("busy", "Another recording is still open: stop it first.")
187
+ }
188
+ let id = (options["recording"] as? NSNumber)?.intValue ?? 0
189
+ let maxDuration = (options["maxDuration"] as? NSNumber).map { $0.doubleValue / 1000 }
190
+ let session = AVAudioSession.sharedInstance()
191
+ let previous = (session.category, session.mode, session.categoryOptions)
192
+ let folder = FileManager.default.temporaryDirectory.appendingPathComponent(
193
+ "recordings", isDirectory: true)
194
+ let name = "recording-\(Int(Date().timeIntervalSince1970 * 1000)).m4a"
195
+ let url = folder.appendingPathComponent(name)
196
+ do {
197
+ // playAndRecord rather than record, so what the app plays (a
198
+ // recording's playback, a sound) isn't silenced while it records,
199
+ // through the speaker rather than the earpiece.
200
+ try session.setCategory(
201
+ .playAndRecord, mode: .default, options: [.defaultToSpeaker, .allowBluetooth])
202
+ try session.setActive(true)
203
+ try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
204
+ let recorder = try AVAudioRecorder(
205
+ url: url,
206
+ settings: [
207
+ AVFormatIDKey: kAudioFormatMPEG4AAC,
208
+ AVSampleRateKey: 44_100,
209
+ AVNumberOfChannelsKey: 1,
210
+ // Enough for a voice, at a fraction of music's bit rate.
211
+ AVEncoderBitRateKey: 64_000,
212
+ AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue,
213
+ ])
214
+ recorder.delegate = self
215
+ recorder.isMeteringEnabled = true
216
+ guard recorder.record() else {
217
+ restore(previous)
218
+ return Self.failure(
219
+ "busy", "The microphone is in use: another app may be recording, or a call is on.")
220
+ }
221
+ recording = Recording(
222
+ id: id, recorder: recorder, url: url, maxDuration: maxDuration, previous: previous)
223
+ ended = nil
224
+ watch()
225
+ startMeter()
226
+ return [:]
227
+ } catch {
228
+ restore(previous)
229
+ return Self.failure("failed", error.localizedDescription)
230
+ }
231
+ }
232
+
233
+ @objc func pause(_ callback: @escaping LynxCallbackBlock) {
234
+ queue.async {
235
+ self.pauseRecording()
236
+ callback([:])
237
+ }
238
+ }
239
+
240
+ @objc func resume(_ callback: @escaping LynxCallbackBlock) {
241
+ queue.async {
242
+ guard var current = self.recording, current.since == nil else {
243
+ callback([:])
244
+ return
245
+ }
246
+ // The session may have been taken by a call meanwhile.
247
+ try? AVAudioSession.sharedInstance().setActive(true)
248
+ guard current.recorder.record() else {
249
+ callback(
250
+ Self.failure(
251
+ "busy", "The microphone is in use: another app may be recording, or a call is on."))
252
+ return
253
+ }
254
+ current.since = ProcessInfo.processInfo.systemUptime
255
+ self.recording = current
256
+ callback([:])
257
+ }
258
+ }
259
+
260
+ @objc func stop(_ callback: @escaping LynxCallbackBlock) {
261
+ queue.async {
262
+ if let clip = self.finish() {
263
+ callback(["clip": clip])
264
+ } else if let clip = self.ended {
265
+ callback(["clip": clip])
266
+ } else {
267
+ callback(Self.failure("failed", "Nothing is recording."))
268
+ }
269
+ }
270
+ }
271
+
272
+ @objc func cancel(_ callback: @escaping LynxCallbackBlock) {
273
+ queue.async {
274
+ if let current = self.recording {
275
+ self.recording = nil
276
+ // Stopped before the session is let go, which would stop it anyway.
277
+ current.recorder.stop()
278
+ current.recorder.deleteRecording()
279
+ self.release(current)
280
+ }
281
+ self.ended = nil
282
+ callback([:])
283
+ }
284
+ }
285
+
286
+ @objc func read(_ options: [String: Any], callback: @escaping LynxCallbackBlock) {
287
+ queue.async {
288
+ let folder = FileManager.default.temporaryDirectory.appendingPathComponent(
289
+ "recordings", isDirectory: true
290
+ ).standardizedFileURL.path
291
+ // Only this module's own recordings: the runtime gives back the uri it
292
+ // was handed, and the module reads no other file.
293
+ guard let text = options["uri"] as? String, let url = URL(string: text), url.isFileURL,
294
+ url.standardizedFileURL.deletingLastPathComponent().path == folder,
295
+ let data = try? Data(contentsOf: url)
296
+ else {
297
+ callback(Self.failure("failed", "The recording couldn't be read."))
298
+ return
299
+ }
300
+ callback(["base64": data.base64EncodedString()])
301
+ }
302
+ }
303
+
304
+ // MARK: - Helpers
305
+
306
+ private func pauseRecording() {
307
+ guard var current = recording, current.since != nil else { return }
308
+ current.recorder.pause()
309
+ current.recorded = current.elapsed
310
+ current.since = nil
311
+ recording = current
312
+ }
313
+
314
+ /// Stops the recording, puts the session back and describes its file.
315
+ private func finish() -> [String: Any]? {
316
+ guard let current = recording else { return nil }
317
+ let durationMs = Int((current.elapsed * 1000).rounded())
318
+ recording = nil
319
+ current.recorder.stop()
320
+ release(current)
321
+ let size =
322
+ (try? FileManager.default.attributesOfItem(atPath: current.url.path)[.size] as? NSNumber)?
323
+ .intValue ?? 0
324
+ return [
325
+ "uri": current.url.absoluteString,
326
+ "name": current.url.lastPathComponent,
327
+ "durationMs": durationMs,
328
+ "mimeType": "audio/mp4",
329
+ "size": size,
330
+ ]
331
+ }
332
+
333
+ private func release(_ current: Recording) {
334
+ timer?.cancel()
335
+ timer = nil
336
+ for observer in observers { NotificationCenter.default.removeObserver(observer) }
337
+ observers = []
338
+ restore(current.previous)
339
+ }
340
+
341
+ /// Puts the audio session back as the recording found it, and lets the
342
+ /// app that was playing (music, a podcast) carry on. Called once the
343
+ /// recorder has stopped. Deactivating also stops what this app plays
344
+ /// through the session, but the shell plays nothing through it itself, and
345
+ /// another app's music resuming after a voice note matters more.
346
+ private func restore(
347
+ _ previous: (AVAudioSession.Category, AVAudioSession.Mode, AVAudioSession.CategoryOptions)
348
+ ) {
349
+ let session = AVAudioSession.sharedInstance()
350
+ try? session.setActive(false, options: .notifyOthersOnDeactivation)
351
+ try? session.setCategory(previous.0, mode: previous.1, options: previous.2)
352
+ }
353
+
354
+ /// The system pausing the recording: a call or Siri taking the session,
355
+ /// or the app going to the background, where it may not record.
356
+ private func watch() {
357
+ let center = NotificationCenter.default
358
+ observers = [
359
+ center.addObserver(
360
+ forName: AVAudioSession.interruptionNotification, object: nil, queue: notifications
361
+ ) { [weak self] note in
362
+ let type = (note.userInfo?[AVAudioSessionInterruptionTypeKey] as? NSNumber)
363
+ .flatMap { AVAudioSession.InterruptionType(rawValue: $0.uintValue) }
364
+ if type == .began { self?.systemPaused() }
365
+ },
366
+ center.addObserver(
367
+ forName: UIApplication.didEnterBackgroundNotification, object: nil, queue: notifications
368
+ ) { [weak self] _ in self?.systemPaused() },
369
+ ]
370
+ }
371
+
372
+ private func systemPaused() {
373
+ guard let current = recording, current.since != nil else { return }
374
+ pauseRecording()
375
+ send(["type": "paused", "recording": current.id])
376
+ }
377
+
378
+ private func startMeter() {
379
+ let source = DispatchSource.makeTimerSource(queue: queue)
380
+ source.schedule(deadline: .now() + Self.levelInterval, repeating: Self.levelInterval)
381
+ source.setEventHandler { [weak self] in self?.tick() }
382
+ timer = source
383
+ source.resume()
384
+ }
385
+
386
+ private func tick() {
387
+ guard let current = recording, current.since != nil else { return }
388
+ let elapsed = current.elapsed
389
+ if let maxDuration = current.maxDuration, elapsed >= maxDuration, let clip = finish() {
390
+ ended = clip
391
+ send(["type": "ended", "recording": current.id, "clip": clip])
392
+ return
393
+ }
394
+ current.recorder.updateMeters()
395
+ let power = current.recorder.averagePower(forChannel: 0)
396
+ let level = max(0, min(1, (power - Self.levelFloor) / -Self.levelFloor))
397
+ send([
398
+ "type": "level", "recording": current.id, "level": level,
399
+ "durationMs": Int((elapsed * 1000).rounded()),
400
+ ])
401
+ }
402
+
403
+ // AVAudioRecorder ends a recording itself only when encoding fails, or the
404
+ // disk fills.
405
+ func audioRecorderEncodeErrorDidOccur(_ recorder: AVAudioRecorder, error: Error?) {
406
+ queue.async {
407
+ guard let current = self.recording, current.recorder === recorder else { return }
408
+ self.recording = nil
409
+ // Nobody can have a clip of it, so its file goes too.
410
+ current.recorder.stop()
411
+ current.recorder.deleteRecording()
412
+ self.release(current)
413
+ self.send(
414
+ [
415
+ "type": "ended", "recording": current.id, "error": "failed",
416
+ "message": error?.localizedDescription ?? "The recording couldn't be encoded.",
417
+ ])
418
+ }
419
+ }
420
+
421
+ func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
422
+ guard !flag else { return }
423
+ audioRecorderEncodeErrorDidOccur(recorder, error: nil)
424
+ }
425
+
426
+ private func send(_ payload: [String: Any]) {
427
+ context?.sendGlobalEvent(Self.eventName, withParams: [payload])
428
+ }
429
+
430
+ private static func failure(_ code: String, _ message: String) -> [String: Any] {
431
+ ["error": code, "message": message]
432
+ }
433
+ }