-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathChatAPI.swift
More file actions
190 lines (154 loc) · 9.2 KB
/
ChatAPI.swift
File metadata and controls
190 lines (154 loc) · 9.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
import Ably
@MainActor
internal final class ChatAPI {
internal enum RequestBody {
case jsonObject([String: JSONValue])
/// Contains an object that can be used the same way as a value returned from `JSONValue.object(…).toAblyCocoaData`. Workaround for JSONValue not being able to indicate to ably-cocoa that a property should be serialized as a MessagePack integer type; TODO revisit in (create an issue for this)
case ablyCocoaData(Any)
}
private let realtime: any InternalRealtimeClientProtocol
private let apiVersionV4 = "/chat/v4"
internal init(realtime: any InternalRealtimeClientProtocol) {
self.realtime = realtime
}
// (CHA-M6) Messages should be queryable from a paginated REST API.
internal func getMessages(roomName: String, params: HistoryParams) async throws(InternalError) -> some PaginatedResult<Message> {
let endpoint = "\(apiVersionV4)/rooms/\(roomName)/messages"
return try await makePaginatedRequest(endpoint, params: params.asQueryItems())
}
internal struct SendMessageReactionParams: Sendable {
internal let type: MessageReactionType
internal let name: String
internal let count: Int?
}
internal struct DeleteMessageReactionParams: Sendable {
internal let type: MessageReactionType
internal let name: String?
}
internal struct MessageReactionResponse: JSONObjectDecodable {
internal let serial: String
internal init(jsonObject: [String: JSONValue]) throws(InternalError) {
serial = try jsonObject.stringValueForKey("serial")
}
}
// (CHA-M3) Messages are sent to Ably via the Chat REST API, using the send method.
// (CHA-M3a) When a message is sent successfully, the caller shall receive a struct representing the Message in response (as if it were received via Realtime event).
internal func sendMessage(roomName: String, params: SendMessageParams) async throws(InternalError) -> Message {
let endpoint = "\(apiVersionV4)/rooms/\(roomName)/messages"
var body: [String: JSONValue] = ["text": .string(params.text)]
// (CHA-M3b) A message may be sent without metadata or headers. When these are not specified by the user, they must be omitted from the REST payload.
if let metadata = params.metadata {
body["metadata"] = .object(metadata)
}
if let headers = params.headers {
body["headers"] = .object(headers.mapValues(\.toJSONValue))
}
// The server returns a complete Message object with all necessary fields
return try await makeRequest(endpoint, method: "POST", body: .jsonObject(body))
}
// (CHA-M8) A client must be able to update a message in a room.
// (CHA-M8a) A client may update a message via the Chat REST API by calling the update method.
internal func updateMessage(roomName: String, with modifiedMessage: Message, details: OperationDetails?) async throws(InternalError) -> Message {
let endpoint = "\(apiVersionV4)/rooms/\(roomName)/messages/\(modifiedMessage.serial)"
var body: [String: JSONValue] = [:]
let messageObject: [String: JSONValue] = [
"text": .string(modifiedMessage.text),
"metadata": .object(modifiedMessage.metadata),
"headers": .object(modifiedMessage.headers.mapValues(\.toJSONValue)),
]
body["message"] = .object(messageObject)
if let description = details?.description {
body["description"] = .string(description)
}
if let metadata = details?.metadata {
body["metadata"] = .object(metadata.mapValues { .string($0) })
}
// (CHA-M8c) An update operation has PUT semantics. If a field is not specified in the update, it is assumed to be removed.
// CHA-M8c is not actually respected here, see https://github.com/ably/ably-chat-swift/issues/333
// (CHA-M8b) When a message is updated successfully via the REST API, the caller shall receive a struct representing the Message in response, as if it were received via Realtime event.
// (CHA-M8b1) The server returns a complete Message object with all necessary fields
return try await makeRequest(endpoint, method: "PUT", body: .jsonObject(body))
}
// (CHA-M9) A client must be able to delete a message in a room.
// (CHA-M9a) A client may delete a message via the Chat REST API by calling the delete method.
internal func deleteMessage(roomName: String, message: Message, details: OperationDetails?) async throws(InternalError) -> Message {
let endpoint = "\(apiVersionV4)/rooms/\(roomName)/messages/\(message.serial)/delete"
var body: [String: JSONValue] = [:]
if let description = details?.description {
body["description"] = .string(description)
}
if let metadata = details?.metadata {
body["metadata"] = .object(metadata.mapValues { .string($0) })
}
// (CHA-M9b) When a message is deleted successfully via the REST API, the caller shall receive a struct representing the Message in response, as if it were received via Realtime event.
// (CHA-M9b1) The server returns a complete Message object with all necessary fields
return try await makeRequest(endpoint, method: "POST", body: .jsonObject(body))
}
internal func getOccupancy(roomName: String) async throws(InternalError) -> OccupancyData {
let endpoint = "\(apiVersionV4)/rooms/\(roomName)/occupancy"
return try await makeRequest(endpoint, method: "GET")
}
// (CHA-MR4) Users should be able to send a reaction to a message via the `send` method of the `MessagesReactions` object
internal func sendReactionToMessage(_ messageSerial: String, roomName: String, params: SendMessageReactionParams) async throws(InternalError) -> MessageReactionResponse {
// (CHA-MR4a1) If the serial passed to this method is invalid: undefined, null, empty string, an error with code 40000 must be thrown.
guard !messageSerial.isEmpty else {
throw ChatError.messageReactionInvalidMessageSerial.toInternalError()
}
let endpoint = "\(apiVersionV4)/rooms/\(roomName)/messages/\(messageSerial)/reactions"
let ablyCocoaBody: [String: Any] = [
"type": params.type.rawValue,
"name": params.name,
"count": params.count ?? 1,
]
return try await makeRequest(endpoint, method: "POST", body: .ablyCocoaData(ablyCocoaBody))
}
// (CHA-MR11) Users should be able to delete a reaction from a message via the `delete` method of the `MessagesReactions` object
internal func deleteReactionFromMessage(_ messageSerial: String, roomName: String, params: DeleteMessageReactionParams) async throws(InternalError) -> MessageReactionResponse {
// (CHA-MR11a1) If the serial passed to this method is invalid: undefined, null, empty string, an error with code 40000 must be thrown.
guard !messageSerial.isEmpty else {
throw ChatError.messageReactionInvalidMessageSerial.toInternalError()
}
let endpoint = "\(apiVersionV4)/rooms/\(roomName)/messages/\(messageSerial)/reactions"
var httpParams: [String: String] = [
"type": params.type.rawValue,
]
httpParams["name"] = params.name
return try await makeRequest(endpoint, method: "DELETE", params: httpParams)
}
private func makeRequest<Response: JSONDecodable>(_ url: String, method: String, params: [String: String]? = nil, body: RequestBody? = nil) async throws(InternalError) -> Response {
let ablyCocoaBody: Any? = if let body {
switch body {
case let .jsonObject(jsonObject):
jsonObject.toAblyCocoaDataDictionary
case let .ablyCocoaData(ablyCocoaData):
ablyCocoaData
}
} else {
nil
}
// (CHA-M3e & CHA-M8d & CHA-M9c) If an error is returned from the REST API, its ErrorInfo representation shall be thrown as the result of the send call.
let paginatedResponse = try await realtime.request(method, path: url, params: params, body: ablyCocoaBody, headers: [:])
guard let firstItem = paginatedResponse.items.first else {
throw ChatError.noItemInResponse.toInternalError()
}
let jsonValue = JSONValue(ablyCocoaData: firstItem)
return try Response(jsonValue: jsonValue)
}
private func makePaginatedRequest<Response: JSONDecodable & Sendable & Equatable>(
_ url: String,
params: [String: String]? = nil,
) async throws(InternalError) -> some PaginatedResult<Response> {
let paginatedResponse = try await realtime.request("GET", path: url, params: params, body: nil, headers: [:])
let jsonValues = paginatedResponse.items.map { JSONValue(ablyCocoaData: $0) }
let items = try jsonValues.map { jsonValue throws(InternalError) in
try Response(jsonValue: jsonValue)
}
return paginatedResponse.toPaginatedResult(items: items)
}
internal enum ChatError: Error {
case noItemInResponse
case messageReactionInvalidMessageSerial
case messageReactionTypeRequired
case messageReactionNameRequired
}
}