Skip to content
This repository has been archived by the owner on Jan 28, 2019. It is now read-only.

Commit

Permalink
SwiftLint + Gardening
Browse files Browse the repository at this point in the history
  • Loading branch information
Peter Zignego committed Jun 9, 2017
1 parent beacb3b commit 41e7f31
Show file tree
Hide file tree
Showing 17 changed files with 108 additions and 57 deletions.
8 changes: 8 additions & 0 deletions .swiftlint.yml
@@ -0,0 +1,8 @@
disabled_rules:
- identifier_name
- function_parameter_count
line_length: 140
excluded: # paths to ignore during linting. Takes precedence over `included`.
- Carthage
- Pods
- Sources/SKServer/Titan
48 changes: 48 additions & 0 deletions SKServer.xcodeproj/project.pbxproj
Expand Up @@ -346,6 +346,7 @@
2684F1791E95AA6900536DCC /* Frameworks */,
2684F17A1E95AA6900536DCC /* Headers */,
2684F17B1E95AA6900536DCC /* Resources */,
2668B5181EEB40E00082DE33 /* SwiftLint */,
);
buildRules = (
);
Expand All @@ -364,6 +365,7 @@
2684F1DE1E95ABD400536DCC /* Frameworks */,
2684F1DF1E95ABD400536DCC /* Headers */,
2684F1E01E95ABD400536DCC /* Resources */,
2668B5191EEB40EA0082DE33 /* SwiftLint */,
);
buildRules = (
);
Expand All @@ -382,6 +384,7 @@
2684F2021E95ABD600536DCC /* Frameworks */,
2684F2031E95ABD600536DCC /* Headers */,
2684F2041E95ABD600536DCC /* Resources */,
2668B51A1EEB40F30082DE33 /* SwiftLint */,
);
buildRules = (
);
Expand Down Expand Up @@ -456,6 +459,51 @@
};
/* End PBXResourcesBuildPhase section */

/* Begin PBXShellScriptBuildPhase section */
2668B5181EEB40E00082DE33 /* SwiftLint */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
name = SwiftLint;
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "if which swiftlint >/dev/null; then\n swiftlint\nelse\n echo \"warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint\"\nfi";
};
2668B5191EEB40EA0082DE33 /* SwiftLint */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
name = SwiftLint;
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "if which swiftlint >/dev/null; then\n swiftlint\nelse\n echo \"warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint\"\nfi";
};
2668B51A1EEB40F30082DE33 /* SwiftLint */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
name = SwiftLint;
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "if which swiftlint >/dev/null; then\n swiftlint\nelse\n echo \"warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint\"\nfi";
};
/* End PBXShellScriptBuildPhase section */

/* Begin PBXSourcesBuildPhase section */
2684F1781E95AA6900536DCC /* Sources */ = {
isa = PBXSourcesBuildPhase;
Expand Down
21 changes: 11 additions & 10 deletions Sources/SKServer/Conformers/SwifterServer.swift
Expand Up @@ -25,46 +25,45 @@ import Foundation
import Swifter

class SwifterServer: SlackKitServer {

let server = HttpServer()
let port: in_port_t
let forceIPV4: Bool

init(port: in_port_t = 8080, forceIPV4: Bool = false, responder: SlackKitResponder) {
self.port = port
self.forceIPV4 = forceIPV4

for route in responder.routes {
server[route.path] = { request in
return route.middleware.respond(to: (request.request, Response())).1.httpResponse
}
}
}

public func start() {
do {
try server.start(port, forceIPv4: forceIPV4)
} catch let error {
print("Server failed to start with error: \(error)")
}
}

deinit {
server.stop()
}
}

extension HttpRequest {
public var request: RequestType {
return Request(self.method, self.path, String(bytes: self.body, encoding: .utf8) ?? "", self.headers.map{($0.key, $0.value)})
return Request(self.method, self.path, String(bytes: self.body, encoding: .utf8) ?? "", self.headers.map {($0.key, $0.value) })
}
}

extension ResponseType {
public var contentType: String? {
return self.headers.first(where: {$0.name.lowercased() == "content-type"})?.value
}

public var httpResponse: HttpResponse {
switch self.code {
case 200 where contentType == nil:
Expand All @@ -76,9 +75,11 @@ extension ResponseType {
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
#if os(Linux)
return .ok(.json(json as! AnyObject))
//swiftlint:disable force_cast
return .ok(.json(json as! AnyObject))
//swiftlint:enable force_cast
#else
return .ok(.json(json as AnyObject))
return .ok(.json(json as AnyObject))
#endif
} catch let error {
return .badRequest(.text(error.localizedDescription))
Expand Down
5 changes: 2 additions & 3 deletions Sources/SKServer/Middleware/MessageActionMiddleware.swift
Expand Up @@ -22,15 +22,14 @@
// THE SOFTWARE.

public struct MessageActionMiddleware: Middleware {

let token: String
let routes: [MessageActionRoute]

public init(token: String, routes: [MessageActionRoute]) {
self.token = token
self.routes = routes
}

public func respond(to request: (RequestType, ResponseType)) -> (RequestType, ResponseType) {
if let form = request.0.formURLEncodedBody.first(where: {$0.name == "ssl_check"}), form.value == "1" {
return (request.0, Response(200))
Expand Down
14 changes: 9 additions & 5 deletions Sources/SKServer/Middleware/OAuthMiddleware.swift
Expand Up @@ -25,20 +25,24 @@ import SKCore
import SKWebAPI

public struct OAuthMiddleware: Middleware {

private let config: OAuthConfig
internal(set) public var authed: ((OAuthResponse) -> Void)? = nil
internal(set) public var authed: ((OAuthResponse) -> Void)?

public init(config: OAuthConfig, authed: ((OAuthResponse) -> Void)? = nil) {
self.config = config
self.authed = authed
}

public func respond(to request: (RequestType, ResponseType)) -> (RequestType, ResponseType) {
guard let response = AuthorizeResponse(queryItems: request.0.query), let code = response.code, response.state == config.state else {
return (request.0, Response(400))
}
let authResponse = WebAPI.oauthAccess(clientID: config.clientID, clientSecret: config.clientSecret, code: code, redirectURI: config.redirectURI)
let authResponse = WebAPI.oauthAccess(
clientID: config.clientID,
clientSecret: config.clientSecret,
code: code,
redirectURI: config.redirectURI
)
self.authed?(OAuthResponse(response: authResponse))
guard let redirect = config.redirectURI else {
return (request.0, Response(200))
Expand Down
5 changes: 2 additions & 3 deletions Sources/SKServer/Middleware/RedirectMiddleware.swift
Expand Up @@ -22,15 +22,14 @@
// SOFTWARE.

public struct RedirectMiddleware: Middleware {

let location: String
let shouldRedirect: (RequestType) -> Bool

public init(redirectTo location: String, if shouldRedirect: @escaping (RequestType) -> Bool) {
self.location = location
self.shouldRedirect = shouldRedirect
}

public func respond(to request: (RequestType, ResponseType)) -> (RequestType, ResponseType) {
if shouldRedirect(request.0) {
return (request.0, Response(code: 302, body: "", headers: [("location", location)]))
Expand Down
16 changes: 8 additions & 8 deletions Sources/SKServer/Middleware/ResponseMiddleware.swift
Expand Up @@ -24,26 +24,24 @@
import Foundation

public struct ResponseMiddleware: Middleware {

let token: String
let response: SKResponse

public init(token: String, response: SKResponse) {
self.token = token
self.response = response
}

public func respond(to request: (RequestType, ResponseType)) -> (RequestType, ResponseType) {
if let respondable = Respondable(request: request.0), respondable.token == token {
return (request.0, Response(response: response))
}
return (request.0, Response(400))
}

private struct Respondable {

let token: String

init?(request: RequestType) {
if let webhook = WebhookRequest(request: request), let token = webhook.token {
self.token = token
Expand Down Expand Up @@ -89,8 +87,10 @@ extension Response {
public init(response: SKResponse) {
if response.attachments == nil {
self.init(200, response.text)
} else if let data = try? JSONSerialization.data(withJSONObject: response.json, options: []), let body = String(data: data, encoding: .utf8) {
self.init(code: 200, body: body, headers: [("content-type","application/json")])
} else if
let data = try? JSONSerialization.data(withJSONObject: response.json, options: []),
let body = String(data: data, encoding: .utf8) {
self.init(code: 200, body: body, headers: [("content-type", "application/json")])
} else {
self.init(400)
}
Expand Down
3 changes: 1 addition & 2 deletions Sources/SKServer/Model/AuthorizeResponse.swift
Expand Up @@ -22,10 +22,9 @@
// THE SOFTWARE.

public struct AuthorizeResponse {

var code: String?
var state: String?

init?(queryItems: [String: String]) {
for item in queryItems {
switch item.key {
Expand Down
3 changes: 1 addition & 2 deletions Sources/SKServer/Model/IncomingWebhook.swift
Expand Up @@ -22,14 +22,13 @@
// THE SOFTWARE.

public struct IncomingWebhook {

public let url: String?
public let channel: String?
public let configurationURL: String?
public let username: String?
public let iconEmoji: String?
public let iconURL: String?

internal init(webhook: [String: Any]?) {
url = webhook?["url"] as? String
channel = webhook?["channel"] as? String
Expand Down
3 changes: 1 addition & 2 deletions Sources/SKServer/Model/MessageActionRequest.swift
Expand Up @@ -24,7 +24,6 @@
import SKCore

public struct MessageActionRequest {

public let action: Action?
public let callbackID: String?
public let team: Team?
Expand All @@ -36,7 +35,7 @@ public struct MessageActionRequest {
public let token: String?
public let originalMessage: Message?
public let responseURL: String?

internal init(response: [String: Any]?) {
action = (response?["actions"] as? [Any])?.map({$0 as? [String: Any]}).first.map({Action(action: $0)})
callbackID = response?["callback_id"] as? String
Expand Down
3 changes: 1 addition & 2 deletions Sources/SKServer/Model/MessageActionRoute.swift
Expand Up @@ -24,10 +24,9 @@
import SKCore

public struct MessageActionRoute {

let action: Action
let middleware: Middleware

public init(action: Action, middleware: Middleware) {
self.action = action
self.middleware = middleware
Expand Down
5 changes: 2 additions & 3 deletions Sources/SKServer/Model/OAuthResponse.swift
Expand Up @@ -24,18 +24,17 @@
import SKCore

public struct OAuthResponse {

public let accessToken: String?
public let scope: [Scope]?
public let userID: String?
public let teamName: String?
public let teamID: String?
public let incomingWebhook: IncomingWebhook?
public let bot: Bot?

internal init(response: [String: Any]?) {
accessToken = response?["access_token"] as? String
scope = (response?["scope"] as? String)?.components(separatedBy: ",").flatMap{Scope(rawValue: $0)}
scope = (response?["scope"] as? String)?.components(separatedBy: ",").flatMap { Scope(rawValue: $0) }
userID = response?["user_id"] as? String
teamName = response?["team_name"] as? String
teamID = response?["team_id"] as? String
Expand Down
3 changes: 1 addition & 2 deletions Sources/SKServer/Model/RequestRoute.swift
Expand Up @@ -22,10 +22,9 @@
// THE SOFTWARE.

public struct RequestRoute {

let path: String
let middleware: Middleware

public init(path: String, middleware: Middleware) {
self.path = path
self.middleware = middleware
Expand Down
9 changes: 4 additions & 5 deletions Sources/SKServer/Model/SKResponse.swift
Expand Up @@ -25,25 +25,24 @@ import Foundation
import SKCore

public struct SKResponse {

let text: String
let responseType: MessageResponseType
let attachments: [Attachment]?

public init(text: String, responseType: MessageResponseType = .inChannel, attachments: [Attachment]? = nil) {
self.responseType = responseType
self.text = text
self.attachments = attachments
}

internal var json: [String: Any] {
var json = [String : Any]()
var json = [String: Any]()
json["text"] = text
json["response_type"] = responseType.rawValue
json["attachments"] = attachments?.map({$0.dictionary})
return json
}

internal var data: Data? {
return try? JSONSerialization.data(withJSONObject: self.json, options: [])
}
Expand Down

0 comments on commit 41e7f31

Please sign in to comment.