Skip to content
Permalink

Comparing changes

Choose two branches to see what’s changed or to start a new pull request. If you need to, you can also or learn more about diff comparisons.

Open a pull request

Create a new pull request by comparing changes across two branches. If you need to, you can also . Learn more about diff comparisons here.
base repository: codefirst/AsakusaSatelliteSwiftClient
Failed to load repositories. Confirm that selected base ref is valid, then try again.
Loading
base: 0.0.1
Choose a base ref
...
head repository: codefirst/AsakusaSatelliteSwiftClient
Failed to load repositories. Confirm that selected head ref is valid, then try again.
Loading
compare: master
Choose a head ref
Loading
15 changes: 8 additions & 7 deletions AsakusaSatellite.podspec
Original file line number Diff line number Diff line change
@@ -1,21 +1,22 @@
Pod::Spec.new do |s|
s.name = "AsakusaSatellite"
s.version = "0.0.1"
s.version = "0.7.1"
s.summary = "AsakusaSatellite API Client for Swift"
s.description = <<-DESC
AsakusaSatellite is a realtime chat application for developers.
DESC
s.homepage = "https://github.com/codefirst/AsakusaSatelliteSwiftClient"
s.license = "MIT"
s.author = { "banjun" => "banjun@gmail.com" }
s.ios.deployment_target = "8.0"
s.osx.deployment_target = "10.10"
s.source = { :git => "https://github.com/codefirst/AsakusaSatelliteSwiftClient.git", :tag => "0.0.1" }
s.ios.deployment_target = "9.0"
s.osx.deployment_target = "10.11"
s.swift_versions = ['5.0']
s.source = { :git => "https://github.com/codefirst/AsakusaSatelliteSwiftClient.git", :tag => s.version.to_s }
s.source_files = 'Classes/*.swift'
s.ios.source_files = 'Classes/ios/*.swift'
s.osx.source_files = ''
s.requires_arc = true
s.dependency "Alamofire", "~> 1.1"
s.dependency "SwiftyJSON", "~> 2.1"
s.dependency "Socket.IO-Client-Swift", "~> 1.1"
s.dependency "Alamofire", "~> 4.0"
s.dependency "Socket.IO-Client-Swift", "~> 15.0"
s.dependency "UTIKit", "~> 2.0"
end
88 changes: 50 additions & 38 deletions Classes/Client.swift
Original file line number Diff line number Diff line change
@@ -8,16 +8,15 @@

import Foundation
import Alamofire
import SwiftyJSON


public class Client {
open class Client {
public let rootURL: String
var apiBaseURL: String { return "\(rootURL)/api/v1" }
var apiBaseURL: String { return rootURL.appendingFormat("api/v1") }
let apiKey: String?

public convenience init(apiKey: String?) {
self.init(rootURL: "https://asakusa-satellite.herokuapp.com", apiKey: apiKey)
self.init(rootURL: "https://asakusa-satellite.herokuapp.com/", apiKey: apiKey)
}

public init(rootURL: String, apiKey: String?) {
@@ -30,75 +29,80 @@ public class Client {
}

private func removeCookies() {
let cs = NSHTTPCookieStorage.sharedHTTPCookieStorage()
for cookie in (cs.cookiesForURL(NSURL(string: rootURL)!) as? [NSHTTPCookie]) ?? [] {
cs.deleteCookie(cookie)
}
AsakusaSatellite.removeCookiesForURL(URL(string: rootURL)!)
}

// MARK: - public APIs
public func serviceInfo(completion: Response<ServiceInfo> -> Void) {
request(Endpoint.ServiceInfo, completion)

open func serviceInfo(_ completion: @escaping (Response<ServiceInfo>) -> Void) {
request(Endpoint.serviceInfo, completion: completion)
}

public func user(completion: Response<User> -> Void) {
request(Endpoint.User, completion)
open func user(_ completion: @escaping (Response<User>) -> Void) {
request(Endpoint.user, completion: completion)
}

public func roomList(completion: Response<Many<Room>> -> Void) {
request(Endpoint.RoomList, completion)
open func roomList(_ completion: @escaping (Response<[Room]>) -> Void) {
request(Endpoint.roomList, completion: completion)
}

public func postMessage(message: String, roomID: String, files: [String], completion: Response<PostMessage> -> Void) {
request(Endpoint.PostMessage(message: message, roomID: roomID, files: files), completion)
open func postMessage(_ message: String, roomID: String, files: [String], completion: @escaping (Response<PostMessage>) -> Void) {
request(Endpoint.postMessage(message: message, roomID: roomID, files: files), completion: completion)
}
public func messageList(roomID: String, count: Int?, sinceID: String?, untilID: String?, order: SortOrder?, completion: Response<Many<Message>> -> Void) {
request(Endpoint.MessageList(roomID: roomID, count: count, sinceID: sinceID, untilID: untilID, order: order), completion)
open func messageList(_ roomID: String, count: Int?, sinceID: String?, untilID: String?, order: SortOrder?, completion: @escaping (Response<[Message]>) -> Void) {
request(Endpoint.messageList(roomID: roomID, count: count, sinceID: sinceID, untilID: untilID, order: order), completion: completion)
}

open func addDevice(_ deviceToken: Data, name: String, completion: @escaping (Response<Nothing>) -> Void) {
request(Endpoint.addDevice(deviceToken: deviceToken, name: name), requestModifier: {$0.validate(statusCode: [200])}, completion: completion)
}

public func messagePusher(roomID: String, completion: (MessagePusherClient? -> Void)) {
open func messagePusher(_ roomID: String, completion: @escaping ((MessagePusherClient?) -> Void)) {
serviceInfo { response in
switch response {
case .Success(let serviceInfo):
if let engine = MessagePusherClient.Engine(messagePusher: serviceInfo().messagePusher) {
case .success(let serviceInfo):
if let engine = MessagePusherClient.Engine(messagePusher: serviceInfo.message_pusher) {
completion(MessagePusherClient(engine: engine, roomID: roomID))
} else {
completion(nil)
}
case .Failure(let error):
case .failure(_):
completion(nil)
}
}
}

// MARK: -

private func request<T: ResponseItem>(endpoint: Endpoint, completion: Response<T> -> Void) {
Alamofire.request(endpoint.URLRequest(apiBaseURL, apiKey: apiKey)).responseJSON { (request, response, object, error) -> Void in
if object == nil || error != nil {
NSLog("failure in Client.request(\(endpoint)): \(error)")
completion(.Failure(error))
} else {
self.completeWithResponse(response, object!, error, completion)
private func request<T: APIModel>(_ endpoint: Endpoint, requestModifier: ((DataRequest) -> DataRequest) = {$0}, completion: @escaping (Response<T>) -> Void) {
requestModifier(Alamofire.request(endpoint.URLRequest(apiBaseURL, apiKey: apiKey))).responseData { response in
switch response.result {
case .success(let value):
let json = try? JSONSerialization.jsonObject(with: value, options: .allowFragments)
let jsonArray = json as? [[String: Any]]
self.completeWithResponse(response.response, jsonArray.flatMap {try? JSONSerialization.data(withJSONObject: endpoint.modifyJSON($0), options: [])} ?? value, nil, completion: completion)
case .failure(let error):
NSLog("%@", "failure in Client.request(\(endpoint)): \(error)")
completion(.failure(error as NSError))
}
}
}

private func completeWithResponse<T: ResponseItem>(response: NSHTTPURLResponse?, _ jsonObject: AnyObject, _ error: NSError?, completion: Response<T> -> Void) {
if let responseItem = T(SwiftyJSON.JSON(jsonObject)) {
completion(Response.Success(responseItem))
} else {
NSLog("failure in completeWithResponse")
completion(.Failure(error))
private func completeWithResponse<T: APIModel>(_ response: HTTPURLResponse?, _ json: Data, _ error: NSError?, completion: (Response<T>) -> Void) {
do {
let responseItem = try T.decoder.decode(T.self, from: json)
completion(Response.success(responseItem))
} catch {
NSLog("%@", "failure in completeWithResponse")
completion(.failure(error as NSError))
}
}
}


public enum Response<T> {
case Success(@autoclosure() -> T) // workaround for Swift compiler error
case Failure(NSError?)
case success(T)
case failure(NSError?)
}


@@ -107,3 +111,11 @@ public enum SortOrder: String {
case Desc = "desc"
}


internal func removeCookiesForURL(_ URL: Foundation.URL) {
let cs = HTTPCookieStorage.shared
for cookie in cs.cookies(for: URL) ?? [] {
cs.deleteCookie(cookie)
}
}

Loading