11import Foundation
2+ import LiveKit
3+
4+ public struct Credentials : Decodable {
5+ let serverUrl : URL
6+ let participantToken : String
7+ }
8+
9+ public protocol CredentialsProvider : Sendable {
10+ func credentials( ) async throws -> Credentials
11+ }
12+
13+ public extension Room {
14+ func connect( credentialsProvider: CredentialsProvider ,
15+ connectOptions: ConnectOptions ? = nil ,
16+ roomOptions: RoomOptions ? = nil ) async throws
17+ {
18+ let credentials = try await credentialsProvider. credentials ( )
19+ try await connect ( url: credentials. serverUrl. absoluteString, token: credentials. participantToken, connectOptions: connectOptions, roomOptions: roomOptions)
20+ }
21+ }
222
323/// A service for fetching LiveKit authentication tokens.
4- /// See [docs](https://docs.livekit.io/home/get-started/authentication) for more information.
5- enum Sandbox {
24+ /// See [docs](https://CredentialsProvider.livekit.io/home/get-started/authentication) for more information.
25+ public struct Sandbox : CredentialsProvider {
26+ private static let url : URL = . init( string: " https://cloud-api.livekit.io/api/sandbox/connection-details " ) !
27+
628 enum Error : Swift . Error {
729 case noResponse
830 case unsuccessfulStatusCode( Int )
931 case decoding( Swift . Error )
1032 }
1133
12- struct Connection : Decodable {
13- let serverUrl : String
14- let participantToken : String
15- let roomName : String
16- let participantName : String
17- }
18-
19- private static let url : String = " https://cloud-api.livekit.io/api/sandbox/connection-details "
20-
21- // TODO: These are not respected anyway (names)
22- static func getConnection( id: String , roomName: String , participantName: String ) async throws -> Connection {
23- var urlComponents = URLComponents ( string: url) !
24- urlComponents. queryItems = [
25- URLQueryItem ( name: " roomName " , value: roomName) ,
26- URLQueryItem ( name: " participantName " , value: participantName) ,
27- ]
34+ let id : String
2835
29- var request = URLRequest ( url: urlComponents. url!)
36+ public func credentials( ) async throws -> Credentials {
37+ var request = URLRequest ( url: Self . url)
3038 request. httpMethod = " POST "
3139 request. addValue ( id. trimmingCharacters ( in: CharacterSet ( charactersIn: " \" " ) ) , forHTTPHeaderField: " X-Sandbox-ID " )
3240
@@ -41,9 +49,15 @@ enum Sandbox {
4149 }
4250
4351 do {
44- return try JSONDecoder ( ) . decode ( Connection . self, from: data)
52+ return try JSONDecoder ( ) . decode ( Credentials . self, from: data)
4553 } catch {
4654 throw Error . decoding ( error)
4755 }
4856 }
4957}
58+
59+ extension Credentials : CredentialsProvider {
60+ public func credentials( ) async throws -> Credentials {
61+ self
62+ }
63+ }
0 commit comments