// Cotton Calling's words from the core, as the shell reads them.//// Every `calls.*` method answers `{ call, effects }` (`crates/cotton-ffi/src/// phone/calls.rs`): the call as the core holds it, and the effects the shell// performs, IN ORDER. The shell decides nothing: it draws `call` and performs// `effects`, and hands back what happened (a tap, a push, a socket frame, the// ICE state, a timer) as the next method.importCottonKitimportFoundation/// One call, as the core answers it (`cotton_core::calling::machine::Call`).publicstructCallState: Equatable, Sendable {publicenumPhase: String, Sendable {case idle, dialling, ringingOut = "ringing_out", ringingIn = "ringing_in", connecting, live, reconnecting, ended }publicvar phase: Phase/// `out`: this person placed it.publicvar outgoing: Boolpublicvar video: Bool/// `p2p` or `sfu`.publicvar mode: Stringpublicvar uuid: Stringpublicvar room: String?publicvar number: String?publicvar person: String?publicvar name: String?/// What this device sends.publicvar sendingAudio: Boolpublicvar sendingVideo: Boolpublicvar liveAt: Date?publicvar endedAt: Date?/// The end reason's word (`hung_up`, `no_answer`, …), once ended.publicvar reason: String?publicstaticlet idle = CallState(json: .object([:]))publicinit(json: JSONValue) { phase = json["phase"]?.string.flatMap(Phase.init(rawValue:)) ?? .idle outgoing = json["direction"]?.string != "in" video = json["video"]?.bool ?? false mode = json["mode"]?.string ?? "p2p" uuid = json["uuid"]?.string ?? "" room = json["room"]?.string number = json["number"]?.string person = json["person"]?.string name = json["name"]?.string sendingAudio = json["own"]?["audio"]?.bool ?? true sendingVideo = json["own"]?["video"]?.bool ?? false liveAt = json["liveAt"]?.double.map { Date(timeIntervalSince1970: $0 / 1000) } endedAt = json["endedAt"]?.double.map { Date(timeIntervalSince1970: $0 / 1000) } reason = json["reason"]?.string }/// A call is under way: anything but idle and ended.publicvar active: Bool { phase != .idle && phase != .ended }}/// An ICE server, as the object handed it.publicstructCallIceServer: Equatable, Sendable {publicvar urls: [String]publicvar username: String?publicvar credential: String?init(json: JSONValue) { urls = json["urls"]?.strings ?? json["urls"]?.string.map { [$0] } ?? [] username = json["username"]?.string credential = json["credential"]?.string }}/// A track on the SFU: its transceiver's mid, whose it is (a pulled one), its name and kind.publicstructCallSfuTrack: Equatable, Sendable {publicvar mid: String?publicvar member: String?publicvar name: Stringpublicvar kind: String?publicinit(mid: String?, member: String?, name: String, kind: String?) {self.mid = midself.member = memberself.name = nameself.kind = kind }init(json: JSONValue) { mid = json["mid"]?.string member = json["member"]?.string name = json["name"]?.string ?? "" kind = json["kind"]?.string }/// As `calls.signal { out: { sfu, tracks } }` takes it.var json: JSONValue {var out: [String: JSONValue] = ["name": .string(name)]iflet mid { out["mid"] = .string(mid) }iflet member { out["member"] = .string(member) }iflet kind { out["kind"] = .string(kind) }return .object(out) }}/// The SDP kinds a peer-to-peer signal carries.publicenumCallSignalKind: String, Sendable {case offer, answer, ice, restart}/// One effect, as the core names it (`Effect`, `#[serde(tag = "do")]`)./// What the shell does with each is `CallCenter.perform`'s.publicenumCallEffect: Equatable, Sendable {case systemCallOutgoing(uuid: String, handle: String, name: String?, video: Bool)case systemCallConnecting(uuid: String)case systemCallConnected(uuid: String, outgoing: Bool)/// `title` is the caller's name once the ring's box opened (else "Cotton");/// `handle` their number, when the box named one.case systemCallIncoming(uuid: String, title: String, handle: String?, video: Bool)case systemCallUpdate(uuid: String, handle: String, name: String?, video: Bool)/// `ios` is CallKit's `CXCallEndedReason` raw value; none asks a `CXEndCallAction`.case systemCallEnded(uuid: String, cause: String, ios: Int?)case startAudio(video: Bool)case stopAudiocase startCameracase stopCameracase playTone(String)case stopTone/// `url` is the socket's whole address (the core puts the object's origin on `path`).case openSocket(url: URL, credential: String, afterMs: Int)case send(frame: JSONValue)case closeSocketcase createPeer(offerer: Bool, iceServers: [CallIceServer])case applyRemote(kind: CallSignalKind, sdp: String)case addCandidate(candidate: String, mid: String?, mline: Int?)case restartIcecase closePeercase setSending(audio: Bool, video: Bool)case timer(afterMs: Int)// A group call through the SFU (chat/CONTRACT.md "Group calls", "The media"): every one is performed, never// a reason to end the call./// Close any peer-to-peer connection and make the one connection to the SFU.case switchToSfu(iceServers: [CallIceServer])/// The microphone (and on a video call the camera) as send-only transceivers of their own, offered and handed/// back as `sfu push` with each one's mid.case pushTracks(audio: Bool, video: Bool)/// The core asked the room for `member`'s tracks: they arrive in the SFU's next offer.case pullTracks(member: String)/// `member` left: their video and their voice go, and `sfu close` is handed back for their mids.case closeTracks(member: String)/// The SFU's SDP: `answer` to a push, or an `offer` to answer (`sfu renegotiate`); an offer's `tracks` say whose/// each new transceiver is.case applySfu(op: String, sdp: String, tracks: [CallSfuTrack])/// The room's roster moved (who is in, talking, muted, taking notes): the screen is asked again.case showRoster/// An effect this build does not know: said in the log, never guessed at.case unknown(String)publicinit(json: JSONValue) {let does = json["do"]?.string ?? ""let uuid = json["uuid"]?.string ?? ""let video = json["video"]?.bool ?? falseswitch does {case"system_call_outgoing":self = .systemCallOutgoing(uuid: uuid, handle: json["handle"]?.string ?? "", name: json["name"]?.string, video: video)case"system_call_connecting": self = .systemCallConnecting(uuid: uuid)case"system_call_connected": self = .systemCallConnected(uuid: uuid, outgoing: json["outgoing"]?.bool ?? false)case"system_call_incoming":self = .systemCallIncoming(uuid: uuid, title: json["title"]?.string ?? "", handle: json["handle"]?.string, video: video)case"system_call_update":self = .systemCallUpdate(uuid: uuid, handle: json["handle"]?.string ?? "", name: json["name"]?.string, video: video)case"system_call_ended":self = .systemCallEnded(uuid: uuid, cause: json["cause"]?.string ?? "", ios: json["ios"]?.int)case"start_audio": self = .startAudio(video: video)case"stop_audio": self = .stopAudiocase"start_camera": self = .startCameracase"stop_camera": self = .stopCameracase"play_tone": self = .playTone(json["tone"]?.string ?? "ringback")case"stop_tone": self = .stopTonecase"open_socket":iflet url = json["url"]?.string.flatMap(URL.init(string:)), let credential = json["credential"]?.string {self = .openSocket(url: url, credential: credential, afterMs: json["after_ms"]?.int ?? 0) } else {self = .unknown("open_socket.no_url") }case"send": self = .send(frame: json["frame"] ?? .null)case"close_socket": self = .closeSocketcase"create_peer":self = .createPeer(offerer: json["offerer"]?.bool ?? false, iceServers: (json["ice_servers"]?.array ?? []).map(CallIceServer.init(json:)))case"apply_remote":iflet kind = json["kind"]?.string.flatMap(CallSignalKind.init(rawValue:)), let sdp = json["sdp"]?.string {self = .applyRemote(kind: kind, sdp: sdp) } else {self = .unknown("apply_remote.no_sdp") }case"add_candidate":self = .addCandidate(candidate: json["candidate"]?.string ?? "", mid: json["mid"]?.string, mline: json["mline"]?.int)case"restart_ice": self = .restartIcecase"close_peer": self = .closePeercase"set_sending": self = .setSending(audio: json["audio"]?.bool ?? true, video: json["video"]?.bool ?? false)case"timer": self = .timer(afterMs: json["after_ms"]?.int ?? 0)case"switch_to_sfu": self = .switchToSfu(iceServers: (json["ice_servers"]?.array ?? []).map(CallIceServer.init(json:)))case"push_tracks": self = .pushTracks(audio: json["audio"]?.bool ?? true, video: video)case"pull_tracks": self = .pullTracks(member: json["member"]?.string ?? "")case"close_tracks": self = .closeTracks(member: json["member"]?.string ?? "")case"apply_remote_sdp":iflet op = json["op"]?.string, let sdp = json["sdp"]?.string {self = .applySfu(op: op, sdp: sdp, tracks: (json["tracks"]?.array ?? []).map(CallSfuTrack.init(json:))) } else {self = .unknown("apply_remote_sdp.no_sdp") }case"show_roster": self = .showRosterdefault: self = .unknown(does) } }}/// One `calls.*` answer: the call, and the effects to perform in order.publicstructCallAnswer: Sendable {publicvar call: CallStatepublicvar effects: [CallEffect]publicinit(json: JSONValue) { call = CallState(json: json["call"] ?? .object([:])) effects = (json["effects"]?.array ?? []).map(CallEffect.init(json:)) }}/// The ICE connection, as `calls.media` takes it.publicenumCallMediaState: String, Sendable {case connected, disconnected, failed}/// The room credential's room, as a ring's UUID is made from it: the room's/// 32 hex is the UUID (`cotton_core::calling::machine::uuid_of_room`), so the/// push's own report and every later one name the same call. Any other shape/// is not a room the Worker makes.publicenumRingUUID {publicstaticfunc of(room: String) -> UUID? {let hex = room.lowercased()guard hex.count == 32, hex.allSatisfy(\.isHexDigit) else { returnnil }let a = Array(hex)let text = "\(String(a[0..<8]))-\(String(a[8..<12]))-\(String(a[12..<16]))-\(String(a[16..<20]))-\(String(a[20..<32]))"return UUID(uuidString: text) }}