|
|
|
@ -9,7 +9,9 @@ public class Connection {
|
|
|
|
|
|
|
|
|
|
public init() { } |
|
|
|
|
|
|
|
|
|
private func authenticatedGET(service: String, |
|
|
|
|
private func authenticatedRequest(service: String, |
|
|
|
|
method: String = "GET", |
|
|
|
|
body: Data? = nil, |
|
|
|
|
queryItems: [String : String] = .init()) |
|
|
|
|
async -> Data? { |
|
|
|
|
guard let token = token else { |
|
|
|
@ -24,7 +26,8 @@ public class Connection {
|
|
|
|
|
let finalURL = urlComponents.url! |
|
|
|
|
|
|
|
|
|
var request = URLRequest(url: finalURL) |
|
|
|
|
request.httpMethod = "GET" |
|
|
|
|
request.httpMethod = method |
|
|
|
|
request.httpBody = body |
|
|
|
|
request.setValue("Bearer: \(token)", forHTTPHeaderField: "Authorization") |
|
|
|
|
|
|
|
|
|
return try? await URLSession.shared.data(for: request).0 |
|
|
|
@ -55,7 +58,7 @@ public class Connection {
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
public func conversations() async -> [Conversation]? { |
|
|
|
|
if let data = await authenticatedGET(service: "conversations") { |
|
|
|
|
if let data = await authenticatedRequest(service: "conversations") { |
|
|
|
|
if let conversations = try? JSONDecoder().decode([RawConversation].self, from: data) { |
|
|
|
|
return conversations.map { |
|
|
|
|
$0.conversation |
|
|
|
@ -67,7 +70,7 @@ public class Connection {
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
public func messages(in conversation: Conversation) async -> [Message]? { |
|
|
|
|
if let data = await authenticatedGET(service: "messages", queryItems: ["guid" : conversation.guid]) { |
|
|
|
|
if let data = await authenticatedRequest(service: "messages", queryItems: ["guid" : conversation.guid]) { |
|
|
|
|
if let messages = try? JSONDecoder().decode([RawMessage].self, from: data) { |
|
|
|
|
return messages.map { |
|
|
|
|
$0.message |
|
|
|
@ -77,6 +80,17 @@ public class Connection {
|
|
|
|
|
|
|
|
|
|
return nil |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
public func send(text: String, in conversation: Conversation) async { |
|
|
|
|
var body = [String : String]() |
|
|
|
|
body["guid"] = conversation.guid |
|
|
|
|
body["body"] = text |
|
|
|
|
let bodyData = try! JSONEncoder().encode(body) |
|
|
|
|
|
|
|
|
|
let _ = await authenticatedRequest(service: "sendMessage", |
|
|
|
|
method: "POST", |
|
|
|
|
body: bodyData) |
|
|
|
|
} |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
extension Connection { |
|
|
|
|