Cotton code
244 lines · 11.0 KB · SwiftRaw
// 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.import CottonKitimport Foundation/// One call, as the core answers it (`cotton_core::calling::machine::Call`).public struct CallState: Equatable, Sendable {    public enum Phase: String, Sendable {        case idle, dialling, ringingOut = "ringing_out", ringingIn = "ringing_in", connecting, live, reconnecting, ended    }    public var phase: Phase    /// `out`: this person placed it.    public var outgoing: Bool    public var video: Bool    /// `p2p` or `sfu`.    public var mode: String    public var uuid: String    public var room: String?    public var number: String?    public var person: String?    public var name: String?    /// What this device sends.    public var sendingAudio: Bool    public var sendingVideo: Bool    public var liveAt: Date?    public var endedAt: Date?    /// The end reason's word (`hung_up`, `no_answer`, …), once ended.    public var reason: String?    public static let idle = CallState(json: .object([:]))    public init(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.    public var active: Bool { phase != .idle && phase != .ended }}/// An ICE server, as the object handed it.public struct CallIceServer: Equatable, Sendable {    public var urls: [String]    public var username: String?    public var 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.public struct CallSfuTrack: Equatable, Sendable {    public var mid: String?    public var member: String?    public var name: String    public var kind: String?    public init(mid: String?, member: String?, name: String, kind: String?) {        self.mid = mid        self.member = member        self.name = name        self.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)]        if let mid { out["mid"] = .string(mid) }        if let member { out["member"] = .string(member) }        if let kind { out["kind"] = .string(kind) }        return .object(out)    }}/// The SDP kinds a peer-to-peer signal carries.public enum CallSignalKind: 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.public enum CallEffect: 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 stopAudio    case startCamera    case stopCamera    case 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 closeSocket    case createPeer(offerer: Bool, iceServers: [CallIceServer])    case applyRemote(kind: CallSignalKind, sdp: String)    case addCandidate(candidate: String, mid: String?, mline: Int?)    case restartIce    case closePeer    case 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)    public init(json: JSONValue) {        let does = json["do"]?.string ?? ""        let uuid = json["uuid"]?.string ?? ""        let video = json["video"]?.bool ?? false        switch 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 = .stopAudio        case "start_camera": self = .startCamera        case "stop_camera": self = .stopCamera        case "play_tone": self = .playTone(json["tone"]?.string ?? "ringback")        case "stop_tone": self = .stopTone        case "open_socket":            if let 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 = .closeSocket        case "create_peer":            self = .createPeer(offerer: json["offerer"]?.bool ?? false, iceServers: (json["ice_servers"]?.array ?? []).map(CallIceServer.init(json:)))        case "apply_remote":            if let 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 = .restartIce        case "close_peer": self = .closePeer        case "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":            if let 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 = .showRoster        default: self = .unknown(does)        }    }}/// One `calls.*` answer: the call, and the effects to perform in order.public struct CallAnswer: Sendable {    public var call: CallState    public var effects: [CallEffect]    public init(json: JSONValue) {        call = CallState(json: json["call"] ?? .object([:]))        effects = (json["effects"]?.array ?? []).map(CallEffect.init(json:))    }}/// The ICE connection, as `calls.media` takes it.public enum CallMediaState: 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.public enum RingUUID {    public static func of(room: String) -> UUID? {        let hex = room.lowercased()        guard hex.count == 32, hex.allSatisfy(\.isHexDigit) else { return nil }        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)    }}