@poolse/native 0.0.0-stage → 3.0.0
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.
- package/CHANGELOG.md +25 -0
- package/LICENSE +206 -0
- package/README.md +148 -2
- package/android/build.gradle +58 -0
- package/android/consumer-rules.pro +11 -0
- package/android/src/main/AndroidManifest.xml +46 -0
- package/android/src/main/java/dev/poolse/callcore/CallCoreRuntime.kt +540 -0
- package/android/src/main/java/dev/poolse/callcore/CallMachine.kt +492 -0
- package/android/src/main/java/dev/poolse/callcore/Ports.kt +132 -0
- package/android/src/main/java/dev/poolse/callcore/android/AndroidRingSurface.kt +383 -0
- package/android/src/main/java/dev/poolse/callcore/android/CallActionReceiver.kt +45 -0
- package/android/src/main/java/dev/poolse/callcore/android/CallCore.kt +578 -0
- package/android/src/main/java/dev/poolse/callcore/android/CallForegroundService.kt +294 -0
- package/android/src/main/java/dev/poolse/callcore/android/CallHttpClient.kt +207 -0
- package/android/src/main/java/dev/poolse/callcore/android/CallMessagingService.kt +161 -0
- package/android/src/main/java/dev/poolse/callcore/android/CallVideo.kt +36 -0
- package/android/src/main/java/dev/poolse/callcore/android/HandlerTimerPort.kt +42 -0
- package/android/src/main/java/dev/poolse/callcore/android/IncomingCallActivity.kt +314 -0
- package/android/src/main/java/dev/poolse/callcore/android/MessageNotifications.kt +353 -0
- package/android/src/main/java/dev/poolse/callcore/android/MissedCallNotification.kt +103 -0
- package/android/src/main/java/dev/poolse/callcore/android/RingBundle.kt +42 -0
- package/android/src/main/java/dev/poolse/callcore/android/SnapshotJson.kt +99 -0
- package/android/src/main/java/expo/modules/poolsecalls/CallLockscreen.kt +42 -0
- package/android/src/main/java/expo/modules/poolsecalls/CallPictureInPicture.kt +92 -0
- package/android/src/main/java/expo/modules/poolsecalls/PoolseCallVideoView.kt +64 -0
- package/android/src/main/java/expo/modules/poolsecalls/PoolseCallsModule.kt +205 -0
- package/android/src/main/livekit/java/dev/poolse/callcore/livekit/LiveKitMediaPort.kt +594 -0
- package/android/src/main/livekit/java/dev/poolse/callcore/livekit/LiveKitVideoSurface.kt +107 -0
- package/android/src/test/java/dev/poolse/callcore/android/CallHttpClientTest.kt +61 -0
- package/app.plugin.js +5 -0
- package/dist/index.cjs +197 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +313 -0
- package/dist/index.d.ts +313 -0
- package/dist/index.js +161 -0
- package/dist/index.js.map +1 -0
- package/expo-module.config.json +11 -0
- package/ios/Core/CallCoreRuntime.swift +543 -0
- package/ios/Core/CallHttpClient.swift +213 -0
- package/ios/Core/CallMachine.swift +394 -0
- package/ios/Core/PORTS_READY.md +93 -0
- package/ios/Core/Ports.swift +238 -0
- package/ios/Core/SnapshotEncoding.swift +122 -0
- package/ios/Module/PoolseCallVideoView.swift +70 -0
- package/ios/Module/PoolseCallsAppDelegateSubscriber.swift +16 -0
- package/ios/Module/PoolseCallsModule.swift +150 -0
- package/ios/Platform/CallCore.swift +623 -0
- package/ios/Platform/CallKitController.swift +326 -0
- package/ios/Platform/CallPictureInPicture.swift +145 -0
- package/ios/Platform/LiveKitMediaPort.swift +798 -0
- package/ios/Platform/LiveKitVideoSurface.swift +68 -0
- package/ios/Platform/MessageNotifications.swift +163 -0
- package/ios/Platform/Ringback.swift +61 -0
- package/ios/Platform/VoipPush.swift +174 -0
- package/ios/PoolseCalls.podspec +68 -0
- package/package.json +53 -4
- package/plugin/index.js +42 -0
- package/plugin/package.json +1 -0
- package/plugin/withCallDelegate.js +35 -0
- package/plugin/withLockscreenCalls.js +84 -0
- package/plugin/withNativeCallMedia.js +19 -0
- package/plugin/withPictureInPicture.js +28 -0
- package/plugin/withRingback.js +86 -0
- package/src/expo-modules-core.d.ts +16 -0
- package/src/index.ts +564 -0
- package/src/react-shims.d.ts +22 -0
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// The HTTP adapter for the contract's three token doors (CALL_CONTRACT.md §4).
|
|
4
|
+
/// Direct port of android/.../CallHttpClient.kt. Every call is a bare REST
|
|
5
|
+
/// request with a bearer token — no session state, no SDK coupling — so the
|
|
6
|
+
/// core can answer a call on a cold launch with nothing but the push's grant.
|
|
7
|
+
///
|
|
8
|
+
/// Fire-and-forget methods (`decline`, `hangup`) retry transient failures a
|
|
9
|
+
/// few times; request/response methods surface `HttpResult` to the runtime,
|
|
10
|
+
/// which owns the retry policy for those (one retry).
|
|
11
|
+
///
|
|
12
|
+
/// Callbacks arrive on URLSession's delegate queue; the runtime hops them
|
|
13
|
+
/// onto its own serial (main) queue.
|
|
14
|
+
public final class CallHttpClient: HttpPort {
|
|
15
|
+
|
|
16
|
+
public static let MAX_BEST_EFFORT_RETRIES = 3
|
|
17
|
+
|
|
18
|
+
/// Read per request: a later `configure()` with another origin takes effect on the next call.
|
|
19
|
+
private let baseUrl: () -> String
|
|
20
|
+
private let session: URLSession
|
|
21
|
+
|
|
22
|
+
public init(baseUrl: @escaping () -> String, session: URLSession = CallHttpClient.defaultSession()) {
|
|
23
|
+
self.baseUrl = baseUrl
|
|
24
|
+
self.session = session
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/// A call action must not hang the ring surface: 9 s total ceiling (6 s
|
|
28
|
+
/// without any data); the runtime retries answer/place once on top, and
|
|
29
|
+
/// both attempts fit inside its 20 s CONNECTING watchdog.
|
|
30
|
+
public static func defaultSession() -> URLSession {
|
|
31
|
+
let config = URLSessionConfiguration.ephemeral
|
|
32
|
+
config.timeoutIntervalForRequest = 6
|
|
33
|
+
config.timeoutIntervalForResource = 9
|
|
34
|
+
config.waitsForConnectivity = false
|
|
35
|
+
config.requestCachePolicy = .reloadIgnoringLocalCacheData
|
|
36
|
+
return URLSession(configuration: config)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
public func answer(callId: String, grant: String, cb: @escaping (HttpResult) -> Void) {
|
|
40
|
+
post("calls/\(callId)/answer", token: grant, body: nil, current: nil, cb: cb)
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
public func join(callId: String, sessionToken: String, cb: @escaping (HttpResult) -> Void) {
|
|
44
|
+
post("calls/\(callId)/join", token: sessionToken, body: nil, current: nil, cb: cb)
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
public func place(conversationId: String, media: String, sessionToken: String,
|
|
48
|
+
cb: @escaping (HttpResult) -> Void) {
|
|
49
|
+
post("conversations/\(conversationId)/calls", token: sessionToken, body: ["media": media], current: nil, cb: cb)
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
public func reconnect(current: CallSessionBundle, cb: @escaping (HttpResult) -> Void) {
|
|
53
|
+
post("calls/\(current.callId)/reconnect", token: current.controlToken, body: nil, current: current, cb: cb)
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
public func decline(callId: String, auth: String, busy: Bool) {
|
|
57
|
+
postBestEffort("calls/\(callId)/decline", token: auth, body: ["reason": busy ? "busy" : "declined"], attempt: 0)
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
public func hangup(callId: String, controlToken: String) {
|
|
61
|
+
postBestEffort("calls/\(callId)/hangup", token: controlToken, body: nil, attempt: 0)
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// MARK: request/response
|
|
65
|
+
|
|
66
|
+
private func post(_ path: String, token: String, body: [String: Any]?, current: CallSessionBundle?,
|
|
67
|
+
cb: @escaping (HttpResult) -> Void) {
|
|
68
|
+
guard let req = request(path, token: token, body: body) else {
|
|
69
|
+
// A malformed base URL is a configuration error, not a timeout.
|
|
70
|
+
cb(.failed(code: "bad_url"))
|
|
71
|
+
return
|
|
72
|
+
}
|
|
73
|
+
session.dataTask(with: req) { data, response, error in
|
|
74
|
+
if error != nil {
|
|
75
|
+
cb(.timeout)
|
|
76
|
+
return
|
|
77
|
+
}
|
|
78
|
+
guard let http = response as? HTTPURLResponse else {
|
|
79
|
+
cb(.timeout)
|
|
80
|
+
return
|
|
81
|
+
}
|
|
82
|
+
let payload = data.flatMap { String(data: $0, encoding: .utf8) }
|
|
83
|
+
cb(CallHttpClient.classify(code: http.statusCode, payload: payload, current: current))
|
|
84
|
+
}.resume()
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// MARK: fire-and-forget with bounded retry
|
|
88
|
+
|
|
89
|
+
private func postBestEffort(_ path: String, token: String, body: [String: Any]?, attempt: Int) {
|
|
90
|
+
guard let req = request(path, token: token, body: body) else { return }
|
|
91
|
+
session.dataTask(with: req) { [weak self] _, response, error in
|
|
92
|
+
guard let self = self else { return }
|
|
93
|
+
let retry: Bool
|
|
94
|
+
if error != nil || !(response is HTTPURLResponse) {
|
|
95
|
+
retry = true
|
|
96
|
+
} else {
|
|
97
|
+
let code = (response as! HTTPURLResponse).statusCode
|
|
98
|
+
// 2xx and 4xx are both terminal here. Only transient 5xx/408/429 retries.
|
|
99
|
+
retry = code == 408 || code == 429 || (500...599).contains(code)
|
|
100
|
+
}
|
|
101
|
+
if retry && attempt < CallHttpClient.MAX_BEST_EFFORT_RETRIES {
|
|
102
|
+
self.postBestEffort(path, token: token, body: body, attempt: attempt + 1)
|
|
103
|
+
}
|
|
104
|
+
}.resume()
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
private func request(_ path: String, token: String, body: [String: Any]?) -> URLRequest? {
|
|
108
|
+
var base = baseUrl()
|
|
109
|
+
while base.hasSuffix("/") { base.removeLast() }
|
|
110
|
+
guard let url = URL(string: "\(base)/v1/\(path)"), url.scheme != nil, url.host != nil else { return nil }
|
|
111
|
+
var req = URLRequest(url: url)
|
|
112
|
+
req.httpMethod = "POST"
|
|
113
|
+
req.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
|
|
114
|
+
req.setValue("application/json", forHTTPHeaderField: "Accept")
|
|
115
|
+
req.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
|
|
116
|
+
req.httpBody = (try? JSONSerialization.data(withJSONObject: body ?? [String: Any]())) ?? Data("{}".utf8)
|
|
117
|
+
req.timeoutInterval = 9
|
|
118
|
+
return req
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// MARK: pure classification (unit tested without a network)
|
|
122
|
+
|
|
123
|
+
private struct ParseError: Error { let what: String }
|
|
124
|
+
|
|
125
|
+
/// Status + body → HttpResult (CALL_CONTRACT.md §4).
|
|
126
|
+
/// 2xx that will not parse → failed("bad_body"); 404/410 → gone;
|
|
127
|
+
/// 401/403 → authFailed; 503 → failed; 408/429/5xx → timeout; other → failed.
|
|
128
|
+
public static func classify(code: Int, payload: String?, current: CallSessionBundle? = nil) -> HttpResult {
|
|
129
|
+
switch code {
|
|
130
|
+
case 200...299:
|
|
131
|
+
if let b = try? parseBundle(payload, current: current) { return .ok(b) }
|
|
132
|
+
return .failed(code: "bad_body")
|
|
133
|
+
case 404, 410:
|
|
134
|
+
return .gone
|
|
135
|
+
case 401, 403:
|
|
136
|
+
return .authFailed(code: errorCode(payload) ?? "http_\(code)")
|
|
137
|
+
case 503:
|
|
138
|
+
return .failed(code: errorCode(payload) ?? "http_503")
|
|
139
|
+
case 408, 429, 500...599:
|
|
140
|
+
return .timeout
|
|
141
|
+
default:
|
|
142
|
+
return .failed(code: errorCode(payload) ?? "http_\(code)")
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/// One parser for answer, join, place AND reconnect. An older server's
|
|
147
|
+
/// reconnect answered only `{livekit:{url,token}}` (maybe a fresh
|
|
148
|
+
/// `control_token`); with `current`, that is applied onto the existing bundle.
|
|
149
|
+
public static func parseBundle(_ payload: String?, current: CallSessionBundle? = nil) throws -> CallSessionBundle {
|
|
150
|
+
guard let payload = payload, let data = payload.data(using: .utf8),
|
|
151
|
+
let root = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any]
|
|
152
|
+
else { throw ParseError(what: "empty or non-object body") }
|
|
153
|
+
guard let livekit = root["livekit"] as? [String: Any] else { throw ParseError(what: "no livekit") }
|
|
154
|
+
let call = root["call"] as? [String: Any]
|
|
155
|
+
guard let call = call else {
|
|
156
|
+
guard let current = current else { throw ParseError(what: "bundle without call") }
|
|
157
|
+
var b = current
|
|
158
|
+
b.livekitUrl = optString(livekit, "url") ?? current.livekitUrl
|
|
159
|
+
b.livekitToken = try getString(livekit, "token")
|
|
160
|
+
b.controlToken = optString(root, "control_token") ?? current.controlToken
|
|
161
|
+
b.ringing = 0
|
|
162
|
+
return b
|
|
163
|
+
}
|
|
164
|
+
guard let controlToken = optString(root, "control_token") ?? current?.controlToken else {
|
|
165
|
+
throw ParseError(what: "bundle without control_token")
|
|
166
|
+
}
|
|
167
|
+
return CallSessionBundle(
|
|
168
|
+
callId: try getString(call, "id"),
|
|
169
|
+
conversationId: try getString(call, "conversation_id"),
|
|
170
|
+
conversationName: optString(call, "conversation_name") ?? current?.conversationName,
|
|
171
|
+
media: optString(call, "media") ?? current?.media ?? "audio",
|
|
172
|
+
created: optBool(root, "created", fallback: true),
|
|
173
|
+
livekitUrl: try getString(livekit, "url"),
|
|
174
|
+
livekitToken: try getString(livekit, "token"),
|
|
175
|
+
controlToken: controlToken,
|
|
176
|
+
kind: optString(call, "kind") ?? current?.kind ?? "call",
|
|
177
|
+
ringing: ((call["ring_states"] as? [String: Any]) ?? [:]).values.filter { ($0 as? String) == "ringing" }.count
|
|
178
|
+
)
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/// The server's envelope is `{"error":{"code":"…"}}`; tolerate a bare string too.
|
|
182
|
+
public static func errorCode(_ payload: String?) -> String? {
|
|
183
|
+
guard let payload = payload, let data = payload.data(using: .utf8),
|
|
184
|
+
let root = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any]
|
|
185
|
+
else { return nil }
|
|
186
|
+
if let err = root["error"] as? [String: Any] { return optString(err, "code") ?? nil }
|
|
187
|
+
return optString(root, "error")
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/// org.json `optString`-or-null semantics: present, non-null, a String, non-empty.
|
|
191
|
+
private static func optString(_ o: [String: Any], _ key: String) -> String? {
|
|
192
|
+
guard let s = o[key] as? String, !s.isEmpty else { return nil }
|
|
193
|
+
return s
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/// org.json (Android) `getString`: required, non-null; numbers/bools coerce to text.
|
|
197
|
+
private static func getString(_ o: [String: Any], _ key: String) throws -> String {
|
|
198
|
+
guard let v = o[key], !(v is NSNull) else { throw ParseError(what: "missing \(key)") }
|
|
199
|
+
if let s = v as? String { return s }
|
|
200
|
+
if let n = v as? NSNumber { return n.stringValue }
|
|
201
|
+
throw ParseError(what: "bad \(key)")
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/// org.json `optBoolean(key, fallback)`: a Bool, or "true"/"false" text.
|
|
205
|
+
private static func optBool(_ o: [String: Any], _ key: String, fallback: Bool) -> Bool {
|
|
206
|
+
if let n = o[key] as? NSNumber, CFGetTypeID(n) == CFBooleanGetTypeID() { return n.boolValue }
|
|
207
|
+
if let s = (o[key] as? String)?.lowercased() {
|
|
208
|
+
if s == "true" { return true }
|
|
209
|
+
if s == "false" { return false }
|
|
210
|
+
}
|
|
211
|
+
return fallback
|
|
212
|
+
}
|
|
213
|
+
}
|
|
@@ -0,0 +1,394 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
// The call state machine — contract cv 1, CALL_CONTRACT.md §7. Direct port of
|
|
4
|
+
// android/.../callcore/CallMachine.kt. Pure: no I/O, no platform, no time.
|
|
5
|
+
// Pinned by contracts/call-core/vectors.json — change the vectors first.
|
|
6
|
+
|
|
7
|
+
/// Inputs, named exactly as in the contract and vectors.
|
|
8
|
+
public enum Event: Equatable {
|
|
9
|
+
/// A ring from push or socket — treated identically. `stale`: deadline passed. Never surface.
|
|
10
|
+
case ring(callId: String, conversationId: String? = nil, media: String = "audio", stale: Bool = false)
|
|
11
|
+
case ringEnded(callId: String, reason: String)
|
|
12
|
+
/// The server finished the call; `reason` only colours an unanswered caller's ended screen.
|
|
13
|
+
case callFinished(callId: String, reason: String? = nil)
|
|
14
|
+
case userAnswer
|
|
15
|
+
case userDecline
|
|
16
|
+
case userPlace(callId: String, conversationId: String? = nil, media: String = "audio")
|
|
17
|
+
case userJoin(callId: String, conversationId: String? = nil)
|
|
18
|
+
case userHangup
|
|
19
|
+
/// Server accepted answer/join/place. `created=false` on place: an existing live call (became a join).
|
|
20
|
+
case httpOk(created: Bool = true)
|
|
21
|
+
case httpGone
|
|
22
|
+
case httpTimeout
|
|
23
|
+
/// Terminal refusal that is NOT "the call is over" (401/403, 503, unparseable 2xx).
|
|
24
|
+
case httpFailed(code: String = "failed")
|
|
25
|
+
case mediaConnected
|
|
26
|
+
case mediaFailed
|
|
27
|
+
case mediaLost
|
|
28
|
+
/// The SFU is recovering on its own. Show it; do not rejoin.
|
|
29
|
+
case mediaReconnecting
|
|
30
|
+
case mediaRecovered
|
|
31
|
+
case remoteJoined
|
|
32
|
+
/// Caller side: every ring resolved without anyone joining.
|
|
33
|
+
case allRingsResolved(outcome: String)
|
|
34
|
+
case ringDeadline
|
|
35
|
+
case reconnectBudgetElapsed
|
|
36
|
+
/// CONNECTING watchdog.
|
|
37
|
+
case connectTimeout
|
|
38
|
+
case lingerElapsed
|
|
39
|
+
/// Call waiting: leave the current call and answer the waiting one.
|
|
40
|
+
case userAnswerWaiting
|
|
41
|
+
/// Call waiting: turn the waiting call away — its caller hears busy.
|
|
42
|
+
case userDeclineWaiting
|
|
43
|
+
/// The waiting call's ring deadline passed.
|
|
44
|
+
case waitingDeadline
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/// Abstract effects — each adapter maps them to its platform.
|
|
48
|
+
public enum Effect: Equatable {
|
|
49
|
+
case showRing, dismissRing, ringtoneStart, ringtoneStop, ringbackStart, ringbackStop
|
|
50
|
+
case httpAnswer, httpJoin, httpPlace, httpDecline
|
|
51
|
+
case httpDeclineBusy(callId: String)
|
|
52
|
+
case httpHangup, httpReconnect, mediaJoin, mediaLeave, callSessionStart, callSessionStop
|
|
53
|
+
case showWaiting, dismissWaiting
|
|
54
|
+
/// The waiting call becomes the current one: retire the old call's
|
|
55
|
+
/// grant/bundle/generation and take the waiting ring's.
|
|
56
|
+
case promoteWaiting
|
|
57
|
+
|
|
58
|
+
public var wire: String {
|
|
59
|
+
switch self {
|
|
60
|
+
case .showRing: return "SHOW_RING"
|
|
61
|
+
case .dismissRing: return "DISMISS_RING"
|
|
62
|
+
case .ringtoneStart: return "RINGTONE_START"
|
|
63
|
+
case .ringtoneStop: return "RINGTONE_STOP"
|
|
64
|
+
case .ringbackStart: return "RINGBACK_START"
|
|
65
|
+
case .ringbackStop: return "RINGBACK_STOP"
|
|
66
|
+
case .httpAnswer: return "HTTP_ANSWER"
|
|
67
|
+
case .httpJoin: return "HTTP_JOIN"
|
|
68
|
+
case .httpPlace: return "HTTP_PLACE"
|
|
69
|
+
case .httpDecline: return "HTTP_DECLINE"
|
|
70
|
+
case .httpDeclineBusy(let callId): return "HTTP_DECLINE_BUSY:\(callId)"
|
|
71
|
+
case .httpHangup: return "HTTP_HANGUP"
|
|
72
|
+
case .httpReconnect: return "HTTP_RECONNECT"
|
|
73
|
+
case .mediaJoin: return "MEDIA_JOIN"
|
|
74
|
+
case .mediaLeave: return "MEDIA_LEAVE"
|
|
75
|
+
case .callSessionStart: return "CALL_SESSION_START"
|
|
76
|
+
case .callSessionStop: return "CALL_SESSION_STOP"
|
|
77
|
+
case .showWaiting: return "SHOW_WAITING"
|
|
78
|
+
case .dismissWaiting: return "DISMISS_WAITING"
|
|
79
|
+
case .promoteWaiting: return "PROMOTE_WAITING"
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
public struct Transition: Equatable {
|
|
85
|
+
public let state: MachineState
|
|
86
|
+
public let effects: [Effect]
|
|
87
|
+
public init(_ state: MachineState, _ effects: [Effect]) {
|
|
88
|
+
self.state = state
|
|
89
|
+
self.effects = effects
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
private extension MachineState {
|
|
94
|
+
func with(phase: Phase? = nil, reason: EndReason?? = nil, direction: Direction?? = nil,
|
|
95
|
+
httpAttempts: Int? = nil) -> MachineState {
|
|
96
|
+
var c = self
|
|
97
|
+
if let phase = phase { c.phase = phase }
|
|
98
|
+
if let reason = reason { c.reason = reason }
|
|
99
|
+
if let direction = direction { c.direction = direction }
|
|
100
|
+
if let httpAttempts = httpAttempts { c.httpAttempts = httpAttempts }
|
|
101
|
+
return c
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
public enum CallMachine {
|
|
106
|
+
|
|
107
|
+
/// Phases that can hold a call waiting beside them: this device is on
|
|
108
|
+
/// (or placing, or joining) a call. A second ring while one is ringING
|
|
109
|
+
/// in is still busy — two rings at once is not a choice anyone can make.
|
|
110
|
+
private static func canHoldWaiting(_ s: MachineState) -> Bool {
|
|
111
|
+
switch s.phase {
|
|
112
|
+
case .ringingOut, .connecting, .active, .reconnecting: return true
|
|
113
|
+
default: return false
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/// The ring surface effects the end-and-answer composite skips: the
|
|
118
|
+
/// waiting call goes straight from waiting to connecting, never ringing.
|
|
119
|
+
private static let ringSurfaceEffects: [Effect] = [.showRing, .ringtoneStart, .ringtoneStop, .dismissRing]
|
|
120
|
+
|
|
121
|
+
public static func transition(_ s: MachineState, _ e: Event) -> Transition {
|
|
122
|
+
guard let w = s.waiting else {
|
|
123
|
+
switch e {
|
|
124
|
+
case let .ring(callId, conversationId, media, stale)
|
|
125
|
+
where !stale && canHoldWaiting(s) && callId != s.callId:
|
|
126
|
+
var next = s
|
|
127
|
+
next.waiting = WaitingCall(callId: callId, conversationId: conversationId, media: media)
|
|
128
|
+
return Transition(next, [.showWaiting])
|
|
129
|
+
case .userAnswerWaiting, .userDeclineWaiting, .waitingDeadline:
|
|
130
|
+
return noop(s)
|
|
131
|
+
default:
|
|
132
|
+
return single(s, e)
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
var cleared = s
|
|
137
|
+
cleared.waiting = nil
|
|
138
|
+
switch e {
|
|
139
|
+
case let .ring(callId, _, _, stale):
|
|
140
|
+
if callId == w.callId || stale { return noop(s) }
|
|
141
|
+
if callId == s.callId { return carry(single(cleared, e), w) }
|
|
142
|
+
return Transition(s, [.httpDeclineBusy(callId: callId)])
|
|
143
|
+
|
|
144
|
+
case let .ringEnded(callId, _) where callId == w.callId:
|
|
145
|
+
return Transition(cleared, [.dismissWaiting])
|
|
146
|
+
case let .callFinished(callId, _) where callId == w.callId:
|
|
147
|
+
return Transition(cleared, [.dismissWaiting])
|
|
148
|
+
case .waitingDeadline:
|
|
149
|
+
return Transition(cleared, [.dismissWaiting])
|
|
150
|
+
case .userDeclineWaiting:
|
|
151
|
+
return Transition(cleared, [.httpDeclineBusy(callId: w.callId), .dismissWaiting])
|
|
152
|
+
|
|
153
|
+
case .userAnswerWaiting:
|
|
154
|
+
// Leaving rings the waiting call (below); answering it at once
|
|
155
|
+
// makes that ring a no-op the surface never sees.
|
|
156
|
+
let left = transition(s, .userHangup)
|
|
157
|
+
guard left.state.phase == .ringingIn, left.state.callId == w.callId else { return noop(s) }
|
|
158
|
+
let answered = single(left.state, .userAnswer)
|
|
159
|
+
let effects = (left.effects + answered.effects).filter { !ringSurfaceEffects.contains($0) }
|
|
160
|
+
return Transition(answered.state, effects)
|
|
161
|
+
|
|
162
|
+
default:
|
|
163
|
+
let t = single(cleared, e)
|
|
164
|
+
guard t.state.phase == .ended || t.state.phase == .idle else { return carry(t, w) }
|
|
165
|
+
// The current call is over while another rings beside it: that
|
|
166
|
+
// ring is now simply THE ring (no ended screen in between).
|
|
167
|
+
let ringing = MachineState(phase: .ringingIn, callId: w.callId, conversationId: w.conversationId,
|
|
168
|
+
direction: .incoming, media: w.media)
|
|
169
|
+
return Transition(ringing, t.effects + [.promoteWaiting, .showRing, .ringtoneStart])
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
private static func carry(_ t: Transition, _ w: WaitingCall) -> Transition {
|
|
174
|
+
var state = t.state
|
|
175
|
+
state.waiting = w
|
|
176
|
+
return Transition(state, t.effects)
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/// The one-call machine: everything that is not about a waiting call.
|
|
180
|
+
private static func single(_ s: MachineState, _ e: Event) -> Transition {
|
|
181
|
+
switch e {
|
|
182
|
+
|
|
183
|
+
case let .ring(callId, conversationId, media, stale):
|
|
184
|
+
return ring(s, callId: callId, conversationId: conversationId, media: media, stale: stale)
|
|
185
|
+
|
|
186
|
+
case let .ringEnded(callId, _):
|
|
187
|
+
if s.phase == .ringingIn && callId == s.callId {
|
|
188
|
+
return Transition(.IDLE, [.ringtoneStop, .dismissRing])
|
|
189
|
+
}
|
|
190
|
+
return noop(s)
|
|
191
|
+
|
|
192
|
+
case let .callFinished(callId, reason):
|
|
193
|
+
guard callId == s.callId else { return noop(s) }
|
|
194
|
+
switch s.phase {
|
|
195
|
+
case .ringingIn:
|
|
196
|
+
return Transition(.IDLE, [.ringtoneStop, .dismissRing])
|
|
197
|
+
case .ringingOut:
|
|
198
|
+
return Transition(s.with(phase: .ended, reason: .some(ringOutcome(reason))),
|
|
199
|
+
[.ringbackStop, .mediaLeave, .callSessionStop])
|
|
200
|
+
case .active, .reconnecting, .connecting:
|
|
201
|
+
return Transition(s.with(phase: .ended, reason: .some(.finished)), [.mediaLeave, .callSessionStop])
|
|
202
|
+
case .ended:
|
|
203
|
+
let outcome = ringOutcome(reason)
|
|
204
|
+
if s.direction == .outgoing && s.reason == .finished && outcome != .finished {
|
|
205
|
+
return Transition(s.with(reason: .some(outcome)), [])
|
|
206
|
+
}
|
|
207
|
+
return noop(s)
|
|
208
|
+
default:
|
|
209
|
+
return noop(s)
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
case .userAnswer:
|
|
213
|
+
if s.phase == .ringingIn {
|
|
214
|
+
return Transition(s.with(phase: .connecting, direction: .some(.incoming), httpAttempts: 1),
|
|
215
|
+
[.ringtoneStop, .dismissRing, .httpAnswer, .callSessionStart])
|
|
216
|
+
}
|
|
217
|
+
return noop(s)
|
|
218
|
+
|
|
219
|
+
case .userDecline:
|
|
220
|
+
if s.phase == .ringingIn {
|
|
221
|
+
return Transition(.IDLE, [.ringtoneStop, .dismissRing, .httpDecline])
|
|
222
|
+
}
|
|
223
|
+
return noop(s)
|
|
224
|
+
|
|
225
|
+
case let .userPlace(callId, conversationId, media):
|
|
226
|
+
if s.phase == .idle || s.phase == .ended {
|
|
227
|
+
return Transition(MachineState(phase: .connecting, callId: callId, conversationId: conversationId,
|
|
228
|
+
direction: .outgoing, media: media, httpAttempts: 1),
|
|
229
|
+
[.httpPlace, .callSessionStart])
|
|
230
|
+
}
|
|
231
|
+
return noop(s)
|
|
232
|
+
|
|
233
|
+
case let .userJoin(callId, conversationId):
|
|
234
|
+
if s.phase == .idle || s.phase == .ended {
|
|
235
|
+
return Transition(MachineState(phase: .connecting, callId: callId, conversationId: conversationId,
|
|
236
|
+
direction: .joined, httpAttempts: 1),
|
|
237
|
+
[.httpJoin, .callSessionStart])
|
|
238
|
+
}
|
|
239
|
+
return noop(s)
|
|
240
|
+
|
|
241
|
+
case .userHangup:
|
|
242
|
+
switch s.phase {
|
|
243
|
+
case .ringingOut:
|
|
244
|
+
return Transition(s.with(phase: .ended, reason: .some(.cancelled)),
|
|
245
|
+
[.ringbackStop, .mediaLeave, .httpHangup, .callSessionStop])
|
|
246
|
+
case .active, .reconnecting, .connecting:
|
|
247
|
+
return Transition(s.with(phase: .ended, reason: .some(.left)),
|
|
248
|
+
[.mediaLeave, .httpHangup, .callSessionStop])
|
|
249
|
+
default:
|
|
250
|
+
return noop(s)
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
case let .httpOk(created):
|
|
254
|
+
if s.phase != .connecting { return noop(s) }
|
|
255
|
+
if s.direction == .outgoing && created {
|
|
256
|
+
return Transition(s.with(phase: .ringingOut), [.mediaJoin, .ringbackStart])
|
|
257
|
+
}
|
|
258
|
+
if s.direction == .outgoing && !created {
|
|
259
|
+
return Transition(s.with(direction: .some(.joined)), [.mediaJoin])
|
|
260
|
+
}
|
|
261
|
+
return Transition(s, [.mediaJoin])
|
|
262
|
+
|
|
263
|
+
case .httpGone:
|
|
264
|
+
switch s.phase {
|
|
265
|
+
case .connecting:
|
|
266
|
+
return Transition(s.with(phase: .ended, reason: .some(.finished)), [.callSessionStop])
|
|
267
|
+
case .reconnecting:
|
|
268
|
+
return Transition(s.with(phase: .ended, reason: .some(.left)), [.mediaLeave, .callSessionStop])
|
|
269
|
+
default:
|
|
270
|
+
return noop(s)
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
case .httpTimeout:
|
|
274
|
+
if s.phase != .connecting { return noop(s) }
|
|
275
|
+
if s.httpAttempts < 2 {
|
|
276
|
+
let retry: Effect
|
|
277
|
+
switch s.direction {
|
|
278
|
+
case .outgoing?: retry = .httpPlace
|
|
279
|
+
case .joined?: retry = .httpJoin
|
|
280
|
+
default: retry = .httpAnswer
|
|
281
|
+
}
|
|
282
|
+
return Transition(s.with(httpAttempts: s.httpAttempts + 1), [retry])
|
|
283
|
+
}
|
|
284
|
+
return Transition(s.with(phase: .ended, reason: .some(.failed)), [.httpHangup, .callSessionStop])
|
|
285
|
+
|
|
286
|
+
case .httpFailed:
|
|
287
|
+
switch s.phase {
|
|
288
|
+
case .connecting:
|
|
289
|
+
return Transition(s.with(phase: .ended, reason: .some(.failed)), [.httpHangup, .callSessionStop])
|
|
290
|
+
case .reconnecting:
|
|
291
|
+
return Transition(s.with(phase: .ended, reason: .some(.failed)), [.mediaLeave, .callSessionStop])
|
|
292
|
+
default:
|
|
293
|
+
return noop(s)
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
case .connectTimeout:
|
|
297
|
+
if s.phase == .connecting {
|
|
298
|
+
return Transition(s.with(phase: .ended, reason: .some(.failed)),
|
|
299
|
+
[.mediaLeave, .httpHangup, .callSessionStop])
|
|
300
|
+
}
|
|
301
|
+
return noop(s)
|
|
302
|
+
|
|
303
|
+
case .mediaConnected:
|
|
304
|
+
switch s.phase {
|
|
305
|
+
case .connecting, .reconnecting: return Transition(s.with(phase: .active), [])
|
|
306
|
+
default: return noop(s)
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
case .mediaFailed:
|
|
310
|
+
switch s.phase {
|
|
311
|
+
case .connecting:
|
|
312
|
+
return Transition(s.with(phase: .ended, reason: .some(.failed)), [.httpHangup, .callSessionStop])
|
|
313
|
+
case .ringingOut:
|
|
314
|
+
return Transition(s.with(phase: .ended, reason: .some(.failed)),
|
|
315
|
+
[.ringbackStop, .mediaLeave, .httpHangup, .callSessionStop])
|
|
316
|
+
default:
|
|
317
|
+
return noop(s)
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
case .mediaLost:
|
|
321
|
+
switch s.phase {
|
|
322
|
+
case .active: return Transition(s.with(phase: .reconnecting), [.httpReconnect])
|
|
323
|
+
case .reconnecting: return Transition(s, [.httpReconnect])
|
|
324
|
+
default: return noop(s)
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
case .mediaReconnecting:
|
|
328
|
+
return s.phase == .active ? Transition(s.with(phase: .reconnecting), []) : noop(s)
|
|
329
|
+
|
|
330
|
+
case .mediaRecovered:
|
|
331
|
+
return s.phase == .reconnecting ? Transition(s.with(phase: .active), []) : noop(s)
|
|
332
|
+
|
|
333
|
+
case .remoteJoined:
|
|
334
|
+
return s.phase == .ringingOut ? Transition(s.with(phase: .active), [.ringbackStop]) : noop(s)
|
|
335
|
+
|
|
336
|
+
case let .allRingsResolved(outcome):
|
|
337
|
+
guard s.phase == .ringingOut else { return noop(s) }
|
|
338
|
+
let reason: EndReason
|
|
339
|
+
switch outcome {
|
|
340
|
+
case "busy_all": reason = .busyAll
|
|
341
|
+
case "no_answer": reason = .noAnswer
|
|
342
|
+
case "cancelled": reason = .cancelled
|
|
343
|
+
default: reason = .declinedAll
|
|
344
|
+
}
|
|
345
|
+
return Transition(s.with(phase: .ended, reason: .some(reason)),
|
|
346
|
+
[.ringbackStop, .mediaLeave, .httpHangup, .callSessionStop])
|
|
347
|
+
|
|
348
|
+
case .ringDeadline:
|
|
349
|
+
return s.phase == .ringingIn ? Transition(.IDLE, [.ringtoneStop, .dismissRing]) : noop(s)
|
|
350
|
+
|
|
351
|
+
case .reconnectBudgetElapsed:
|
|
352
|
+
if s.phase == .reconnecting {
|
|
353
|
+
return Transition(s.with(phase: .ended, reason: .some(.connectionLost)),
|
|
354
|
+
[.mediaLeave, .httpHangup, .callSessionStop])
|
|
355
|
+
}
|
|
356
|
+
return noop(s)
|
|
357
|
+
|
|
358
|
+
case .lingerElapsed:
|
|
359
|
+
return s.phase == .ended ? Transition(.IDLE, []) : noop(s)
|
|
360
|
+
|
|
361
|
+
case .userAnswerWaiting, .userDeclineWaiting, .waitingDeadline:
|
|
362
|
+
return noop(s) // handled by `transition`, which owns the waiting slot
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
private static func ring(_ s: MachineState, callId: String, conversationId: String?, media: String,
|
|
367
|
+
stale: Bool) -> Transition {
|
|
368
|
+
if stale { return noop(s) }
|
|
369
|
+
// Already showing this very ring (push + socket race): one surface.
|
|
370
|
+
if s.phase == .ringingIn && callId == s.callId { return noop(s) }
|
|
371
|
+
// A fresh ring on idle — or over a lingering ended screen.
|
|
372
|
+
if s.phase == .idle || s.phase == .ended {
|
|
373
|
+
return Transition(MachineState(phase: .ringingIn, callId: callId, conversationId: conversationId,
|
|
374
|
+
direction: .incoming, media: media),
|
|
375
|
+
[.showRing, .ringtoneStart])
|
|
376
|
+
}
|
|
377
|
+
// Busy ringing another call (a call in progress holds it waiting
|
|
378
|
+
// instead — see `transition`): auto-decline the newcomer.
|
|
379
|
+
return Transition(s, [.httpDeclineBusy(callId: callId)])
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
/// A finish push's reason, read as the caller's unanswered outcome.
|
|
383
|
+
private static func ringOutcome(_ reason: String?) -> EndReason {
|
|
384
|
+
switch reason {
|
|
385
|
+
case "no_answer"?, "timeout"?: return .noAnswer
|
|
386
|
+
case "declined_all"?, "declined"?: return .declinedAll
|
|
387
|
+
case "busy_all"?: return .busyAll
|
|
388
|
+
case "cancelled"?: return .cancelled
|
|
389
|
+
default: return .finished
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
private static func noop(_ s: MachineState) -> Transition { Transition(s, []) }
|
|
394
|
+
}
|