Skip to content
This repository has been archived by the owner on Dec 2, 2022. It is now read-only.

Commit

Permalink
Merge pull request #67 from pvzig/0.0.6
Browse files Browse the repository at this point in the history
0.0.6
  • Loading branch information
pvzig authored Jan 6, 2017
2 parents 59e7d6c + eccf73c commit c58abcd
Show file tree
Hide file tree
Showing 5 changed files with 132 additions and 134 deletions.
4 changes: 3 additions & 1 deletion SlackKit/Sources/Client+EventDispatching.swift
Original file line number Diff line number Diff line change
Expand Up @@ -153,8 +153,10 @@ internal extension SlackClient {
subteamAddedSelf(event)
case .subteamSelfRemoved:
subteamRemovedSelf(event)
case .error:
print("Error: \(anEvent)")
case .unknown:
print("Unknown event of type: \(anEvent["type"] ?? "No Type Information")")
print("Unsupported event of type: \(anEvent["type"] ?? "No Type Information")")
}
}

Expand Down
3 changes: 1 addition & 2 deletions SlackKit/Sources/Event.swift
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@
// THE SOFTWARE.

internal enum EventType: String {

case hello = "hello"
case message = "message"
case userTyping = "user_typing"
Expand Down Expand Up @@ -93,11 +92,11 @@ internal enum EventType: String {
case subteamSelfAdded = "subteam_self_added"
case subteamSelfRemoved = "subteam_self_removed"
case ok = "ok"
case error = "error"
case unknown = "unknown"
}

internal enum MessageSubtype: String {

case botMessage = "bot_message"
case meMessage = "me_message"
case messageChanged = "message_changed"
Expand Down
15 changes: 0 additions & 15 deletions SlackKit/Sources/Extensions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -39,18 +39,3 @@ internal extension String {
return escapedString
}
}

internal extension Dictionary where Key: ExpressibleByStringLiteral, Value: Any {

var requestStringFromParameters: String {
var requestString = ""
for key in self.keys {
if let value = self[key] as? String, let encodedValue = value.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) {
requestString += "&\(key)=\(encodedValue)"
} else if let value = self[key] {
requestString += "&\(key)=\(value)"
}
}
return requestString
}
}
107 changes: 65 additions & 42 deletions SlackKit/Sources/NetworkInterface.swift
Original file line number Diff line number Diff line change
Expand Up @@ -38,30 +38,20 @@ internal struct NetworkInterface {
}
}

internal func request(_ endpoint: Endpoint, token: String, parameters: [String: Any]?, successClosure: ([String: Any])->Void, errorClosure: (SlackError)->Void) {
var requestString = "\(apiUrl)\(endpoint.rawValue)?token=\(token)"
if let params = parameters {
requestString += params.requestStringFromParameters
internal func request(_ endpoint: Endpoint, parameters: [String: Any?], successClosure: @escaping ([String: Any])->Void, errorClosure: @escaping (SlackError)->Void) {
var components = URLComponents(string: "\(apiUrl)\(endpoint.rawValue)")
if parameters.count > 0 {
components?.queryItems = filterNilParameters(parameters).map { URLQueryItem(name: $0.0, value: "\($0.1)") }
}
guard let requestString = components?.string else {
errorClosure(SlackError.clientNetworkError)
return
}

do {
let contentNegotiation = ContentNegotiationMiddleware(mediaTypes: [.json, .urlEncodedForm], mode: .client)
var response = try client?.get(requestString, middleware: [contentNegotiation])
if let buffer = try response?.body.becomeBuffer(deadline: 3.seconds.fromNow()) {
let data = Data(bytes: buffer.bytes)
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
if let result = json as? [String: Any] {
if (result["ok"] as? Bool == true) {
successClosure(result)
} else {
if let errorString = result["error"] as? String {
throw SlackError(rawValue: errorString) ?? SlackError.unknownError
} else {
throw SlackError.unknownError
}
}
}
}
let response = try client?.get(requestString, middleware: [contentNegotiation])
successClosure(try handleResponse(response))
} catch let error {
if let slackError = error as? SlackError {
errorClosure(slackError)
Expand All @@ -71,17 +61,21 @@ internal struct NetworkInterface {
}
}

internal func uploadRequest(token: String, data: Data, parameters: [String: Any]?, successClosure: ([String: Any])->Void, errorClosure: (SlackError)->Void) {
var requestString = "\(apiUrl)\(Endpoint.filesUpload.rawValue)?token=\(token)"
if let params = parameters {
requestString = requestString + params.requestStringFromParameters
internal func uploadRequest(data: Data, parameters: [String: Any?], successClosure: @escaping ([String: Any])->Void, errorClosure: @escaping (SlackError)->Void) {
var components = URLComponents(string: "\(apiUrl)\(Endpoint.filesUpload.rawValue)")
if parameters.count > 0 {
components?.queryItems = filterNilParameters(parameters).map { URLQueryItem(name: $0.0, value: "\($0.1)") }
}
guard let requestString = components?.string else {
errorClosure(SlackError.clientNetworkError)
return
}

let boundaryConstant = randomBoundary()
let boundaryStart = "--\(boundaryConstant)\r\n"
let boundaryEnd = "\r\n--\(boundaryConstant)--\r\n"
let contentDispositionString = "Content-Disposition: form-data; name=\"file\"; filename=\"\(parameters!["filename"])\"\r\n"
let contentTypeString = "Content-Type: \(parameters!["filetype"])\r\n\r\n"
let contentDispositionString = "Content-Disposition: form-data; name=\"file\"; filename=\"\(parameters["filename"])\"\r\n"
let contentTypeString = "Content-Type: \(parameters["filetype"])\r\n\r\n"

guard let boundaryStartData = boundaryStart.data(using: .utf8), let dispositionData = contentDispositionString.data(using: .utf8), let contentTypeData = contentTypeString.data(using: .utf8), let boundaryEndData = boundaryEnd.data(using: .utf8) else {
errorClosure(SlackError.clientNetworkError)
Expand All @@ -95,33 +89,62 @@ internal struct NetworkInterface {
requestBodyData.append(contentsOf: boundaryEndData)

let header: Headers = ["Content-Type":"multipart/form-data; boundary=\(boundaryConstant)"]

let body = Buffer([UInt8](requestBodyData))

do {
let body = Buffer([UInt8](requestBodyData))
var response = try client?.post(requestString, headers: header, body: body)
if let buffer = try response?.body.becomeBuffer(deadline: 3.seconds.fromNow()) {
let response = try client?.post(requestString, headers: header, body: body)
successClosure(try handleResponse(response))
} catch let error {
if let slackError = error as? SlackError {
errorClosure(slackError)
} else {
errorClosure(SlackError.unknownError)
}
}
}

private func handleResponse(_ response: Response?) throws -> [String: Any] {
guard var response = response else {
throw SlackError.clientNetworkError
}
do {
let buffer = try response.body.becomeBuffer(deadline: 3.seconds.fromNow())
switch response.statusCode {
case 200:
let data = Data(bytes: buffer.bytes)
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
if let result = json as? [String: Any] {
if (result["ok"] as? Bool == true) {
successClosure(result)
if let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any] {
if json["ok"] as? Bool == true {
return json
} else if let errorString = json["error"] as? String {
throw SlackError(rawValue: errorString) ?? .unknownError
} else {
if let errorString = result["error"] as? String {
throw SlackError(rawValue: errorString) ?? SlackError.unknownError
} else {
throw SlackError.unknownError
}
throw SlackError.clientJSONError
}
} else {
throw SlackError.unknownError
}
case 429:
throw SlackError.tooManyRequests
default:
throw SlackError.clientNetworkError
}

} catch let error {
if let slackError = error as? SlackError {
errorClosure(slackError)
throw slackError
} else {
errorClosure(SlackError.unknownError)
throw SlackError.unknownError
}
}
}

private func filterNilParameters(_ parameters: [String: Any?]) -> [String: Any] {
var finalParameters = [String: Any]()
for (key, value) in parameters {
if let unwrapped = value {
finalParameters[key] = unwrapped
}
}
return finalParameters
}

private func randomBoundary() -> String {
Expand Down
Loading

0 comments on commit c58abcd

Please sign in to comment.