From 1b4b571be66e28cf20632e289c4c1a9b6fafce60 Mon Sep 17 00:00:00 2001 From: Erik Date: Mon, 11 Apr 2016 18:58:02 -0400 Subject: [PATCH 01/14] bump version --- README.md | 6 +++--- Socket.IO-Client-Swift.podspec | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 73f2882..5f21917 100644 --- a/README.md +++ b/README.md @@ -88,7 +88,7 @@ Carthage ----------------- Add this line to your `Cartfile`: ``` -github "socketio/socket.io-client-swift" ~> 6.0.0 # Or latest version +github "socketio/socket.io-client-swift" ~> 6.1.0 # Or latest version ``` Run `carthage update --platform ios,macosx`. @@ -102,7 +102,7 @@ source 'https://github.com/CocoaPods/Specs.git' platform :ios, '8.0' use_frameworks! -pod 'Socket.IO-Client-Swift', '~> 6.0.0' # Or latest version +pod 'Socket.IO-Client-Swift', '~> 6.1.0' # Or latest version ``` Install pods: @@ -130,7 +130,7 @@ CocoaSeeds Add this line to your `Seedfile`: ``` -github "socketio/socket.io-client-swift", "v6.0.0", :files => "Source/*.swift" # Or latest version +github "socketio/socket.io-client-swift", "v6.1.0", :files => "Source/*.swift" # Or latest version ``` Run `seed install`. diff --git a/Socket.IO-Client-Swift.podspec b/Socket.IO-Client-Swift.podspec index 42a8ef9..52ae33e 100644 --- a/Socket.IO-Client-Swift.podspec +++ b/Socket.IO-Client-Swift.podspec @@ -1,7 +1,7 @@ Pod::Spec.new do |s| s.name = "Socket.IO-Client-Swift" s.module_name = "SocketIOClientSwift" - s.version = "6.0.0" + s.version = "6.1.0" s.summary = "Socket.IO-client for iOS and OS X" s.description = <<-DESC Socket.IO-client for iOS and OS X. @@ -14,7 +14,7 @@ Pod::Spec.new do |s| s.ios.deployment_target = '8.0' s.osx.deployment_target = '10.10' s.tvos.deployment_target = '9.0' - s.source = { :git => "https://github.com/socketio/socket.io-client-swift.git", :tag => 'v6.0.0' } + s.source = { :git => "https://github.com/socketio/socket.io-client-swift.git", :tag => 'v6.1.0' } s.source_files = "Source/**/*.swift" s.requires_arc = true # s.dependency 'Starscream', '~> 0.9' # currently this repo includes Starscream swift files From 44ee94d2ac0ddcfeddabd72aba0bd15be6dba243 Mon Sep 17 00:00:00 2001 From: Erik Date: Tue, 26 Apr 2016 15:28:08 -0400 Subject: [PATCH 02/14] refactors --- Source/SocketEngine.swift | 29 +++++++++++------------------ Source/SocketEngineSpec.swift | 2 +- Source/SocketEngineWebsocket.swift | 2 -- 3 files changed, 12 insertions(+), 21 deletions(-) diff --git a/Source/SocketEngine.swift b/Source/SocketEngine.swift index e886cad..857e6d8 100644 --- a/Source/SocketEngine.swift +++ b/Source/SocketEngine.swift @@ -34,6 +34,7 @@ public final class SocketEngine : NSObject, SocketEnginePollable, SocketEngineWe (urlPolling, urlWebSocket) = createURLs() } } + public var postWait = [String]() public var waitingForPoll = false public var waitingForPost = false @@ -133,23 +134,16 @@ public final class SocketEngine : NSObject, SocketEnginePollable, SocketEngineWe allowLossyConversion: false) else { return } do { - if let dict = try NSJSONSerialization.JSONObjectWithData(stringData, - options: NSJSONReadingOptions.MutableContainers) as? NSDictionary { - guard let code = dict["code"] as? Int else { return } - guard let error = dict["message"] as? String else { return } - - switch code { - case 0: // Unknown transport - didError(error) - case 1: // Unknown sid. - didError(error) - case 2: // Bad handshake request - didError(error) - case 3: // Bad request - didError(error) - default: - didError(error) - } + if let dict = try NSJSONSerialization.JSONObjectWithData(stringData, options: .MutableContainers) as? NSDictionary { + guard let error = dict["message"] as? String else { return } + + /* + 0: Unknown transport + 1: Unknown sid + 2: Bad handshake request + 3: Bad request + */ + didError(error) } } catch { didError("Got unknown error from server \(msg)") @@ -393,7 +387,6 @@ public final class SocketEngine : NSObject, SocketEnginePollable, SocketEngineWe } } catch { didError("Error parsing open packet") - return } } diff --git a/Source/SocketEngineSpec.swift b/Source/SocketEngineSpec.swift index 2fde9f3..58b5450 100644 --- a/Source/SocketEngineSpec.swift +++ b/Source/SocketEngineSpec.swift @@ -46,7 +46,7 @@ import Foundation var urlPolling: NSURL { get } var urlWebSocket: NSURL { get } var websocket: Bool { get } - optional var ws: WebSocket? { get } + var ws: WebSocket? { get } init(client: SocketEngineClient, url: NSURL, options: NSDictionary?) diff --git a/Source/SocketEngineWebsocket.swift b/Source/SocketEngineWebsocket.swift index a173250..e1b0ba8 100644 --- a/Source/SocketEngineWebsocket.swift +++ b/Source/SocketEngineWebsocket.swift @@ -27,8 +27,6 @@ import Foundation /// Protocol that is used to implement socket.io WebSocket support public protocol SocketEngineWebsocket : SocketEngineSpec, WebSocketDelegate { - var ws: WebSocket? { get } - func sendWebSocketMessage(str: String, withType type: SocketEnginePacketType, withData datas: [NSData]) } From 8e1434e63b67869b3b9c0474f70e3fcd43feabdb Mon Sep 17 00:00:00 2001 From: Erik Date: Wed, 27 Apr 2016 14:38:11 -0400 Subject: [PATCH 03/14] change status names, execute engine connect on emitQueue --- Source/SocketEngine.swift | 7 +++++-- Source/SocketEnginePollable.swift | 1 + Source/SocketIOClient.swift | 17 +++++++++-------- Source/SocketIOClientStatus.swift | 19 ++++--------------- 4 files changed, 19 insertions(+), 25 deletions(-) diff --git a/Source/SocketEngine.swift b/Source/SocketEngine.swift index 857e6d8..add2f02 100644 --- a/Source/SocketEngine.swift +++ b/Source/SocketEngine.swift @@ -198,7 +198,9 @@ public final class SocketEngine : NSObject, SocketEnginePollable, SocketEngineWe } } - doLongPoll(reqPolling) + dispatch_async(emitQueue) { + self.doLongPoll(reqPolling) + } } private func createURLs() -> (NSURL, NSURL) { @@ -280,7 +282,8 @@ public final class SocketEngine : NSObject, SocketEnginePollable, SocketEngineWe DefaultSocketLogger.Logger.log("Engine is being closed.", type: logType) if closed { - return postSendClose(nil, nil, nil) + client?.engineDidClose(reason) + return } if websocket { diff --git a/Source/SocketEnginePollable.swift b/Source/SocketEnginePollable.swift index c419e51..70a9e56 100644 --- a/Source/SocketEnginePollable.swift +++ b/Source/SocketEnginePollable.swift @@ -105,6 +105,7 @@ extension SocketEnginePollable { return } + DefaultSocketLogger.Logger.log("Doing polling request", type: "SocketEnginePolling") session?.dataTaskWithRequest(req, completionHandler: callback).resume() diff --git a/Source/SocketIOClient.swift b/Source/SocketIOClient.swift index 99fa5f8..02cda38 100644 --- a/Source/SocketIOClient.swift +++ b/Source/SocketIOClient.swift @@ -131,8 +131,7 @@ public final class SocketIOClient : NSObject, SocketEngineClient, SocketParsable assert(timeoutAfter >= 0, "Invalid timeout: \(timeoutAfter)") guard status != .Connected else { - DefaultSocketLogger.Logger.log("Tried connecting on an already connected socket", - type: logType) + DefaultSocketLogger.Logger.log("Tried connecting on an already connected socket", type: logType) return } @@ -149,8 +148,8 @@ public final class SocketIOClient : NSObject, SocketEngineClient, SocketParsable let time = dispatch_time(DISPATCH_TIME_NOW, Int64(timeoutAfter) * Int64(NSEC_PER_SEC)) dispatch_after(time, handleQueue) {[weak self] in - if let this = self where this.status != .Connected && this.status != .Closed { - this.status = .Closed + if let this = self where this.status != .Connected && this.status != .Disconnected { + this.status = .Disconnected this.engine?.disconnect("Connect timeout") handler?() @@ -187,11 +186,11 @@ public final class SocketIOClient : NSObject, SocketEngineClient, SocketParsable } func didDisconnect(reason: String) { - guard status != .Closed else { return } + guard status != .Disconnected else { return } DefaultSocketLogger.Logger.log("Disconnected: %@", type: logType, args: reason) - status = .Closed + status = .Disconnected reconnects = false // Make sure the engine is actually dead. @@ -202,6 +201,8 @@ public final class SocketIOClient : NSObject, SocketEngineClient, SocketParsable /// Disconnects the socket. Only reconnect the same socket if you know what you're doing. /// Will turn off automatic reconnects. public func disconnect() { + assert(status != .NotConnected, "Tried closing a NotConnected client") + DefaultSocketLogger.Logger.log("Closing socket", type: logType) reconnects = false @@ -267,11 +268,11 @@ public final class SocketIOClient : NSObject, SocketEngineClient, SocketParsable public func engineDidClose(reason: String) { waitingPackets.removeAll() - if status != .Closed { + if status != .Disconnected { status = .NotConnected } - if status == .Closed || !reconnects { + if status == .Disconnected || !reconnects { didDisconnect(reason) } else if !reconnecting { reconnecting = true diff --git a/Source/SocketIOClientStatus.swift b/Source/SocketIOClientStatus.swift index 09626b8..3d39e4a 100644 --- a/Source/SocketIOClientStatus.swift +++ b/Source/SocketIOClientStatus.swift @@ -24,19 +24,8 @@ import Foundation -@objc public enum SocketIOClientStatus : Int, CustomStringConvertible { - case NotConnected, Closed, Connecting, Connected - - public var description: String { - switch self { - case NotConnected: - return "Not Connected" - case Closed: - return "Closed" - case Connecting: - return "Connecting" - case Connected: - return "Connected" - } - } +@objc public enum SocketIOClientStatus : Int { + // NotConnected: initial state + // Disconnected: connected before + case NotConnected, Disconnected, Connecting, Connected } \ No newline at end of file From 82e7882497fd2b8b4ef2b44533f7d690e4c0fb40 Mon Sep 17 00:00:00 2001 From: Erik Date: Wed, 27 Apr 2016 18:32:38 -0400 Subject: [PATCH 04/14] add rest of emitWithAck for objc test --- SocketIO-MacTests/SocketObjectiveCTest.m | 4 +++- Source/SocketEnginePollable.swift | 1 - 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/SocketIO-MacTests/SocketObjectiveCTest.m b/SocketIO-MacTests/SocketObjectiveCTest.m index 8372112..f3f70e3 100644 --- a/SocketIO-MacTests/SocketObjectiveCTest.m +++ b/SocketIO-MacTests/SocketObjectiveCTest.m @@ -35,7 +35,9 @@ } - (void)testEmitWithAckSyntax { - [self.socket emitWithAck:@"testAckEmit" withItems:@[@YES]]; + [self.socket emitWithAck:@"testAckEmit" withItems:@[@YES]](0, ^(NSArray* data) { + + }); } - (void)testOffSyntax { diff --git a/Source/SocketEnginePollable.swift b/Source/SocketEnginePollable.swift index 70a9e56..c419e51 100644 --- a/Source/SocketEnginePollable.swift +++ b/Source/SocketEnginePollable.swift @@ -105,7 +105,6 @@ extension SocketEnginePollable { return } - DefaultSocketLogger.Logger.log("Doing polling request", type: "SocketEnginePolling") session?.dataTaskWithRequest(req, completionHandler: callback).resume() From 9ff90f511e9f7e2b849ed35a04fe012722c46931 Mon Sep 17 00:00:00 2001 From: Yannick Loriot Date: Wed, 4 May 2016 12:56:14 +0200 Subject: [PATCH 05/14] Fixing url encoding for connect params --- .../project.pbxproj | 24 ++++++++++++++ Source/NSCharacterSet.swift | 31 +++++++++++++++++++ Source/SocketEngine.swift | 13 +++++--- Source/SocketEngineSpec.swift | 4 +-- Source/String.swift | 31 +++++++++++++++++++ 5 files changed, 96 insertions(+), 7 deletions(-) create mode 100644 Source/NSCharacterSet.swift create mode 100644 Source/String.swift diff --git a/Socket.IO-Client-Swift.xcodeproj/project.pbxproj b/Socket.IO-Client-Swift.xcodeproj/project.pbxproj index f209032..97318d8 100644 --- a/Socket.IO-Client-Swift.xcodeproj/project.pbxproj +++ b/Socket.IO-Client-Swift.xcodeproj/project.pbxproj @@ -128,6 +128,12 @@ 74ABF7771C3991C10078C657 /* SocketIOClientSpec.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74ABF7761C3991C10078C657 /* SocketIOClientSpec.swift */; }; 74F124F01BC574CF002966F4 /* SocketBasicPacketTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74F124EF1BC574CF002966F4 /* SocketBasicPacketTest.swift */; }; 74F124F11BC574CF002966F4 /* SocketBasicPacketTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74F124EF1BC574CF002966F4 /* SocketBasicPacketTest.swift */; }; + CEBA56961CDA0B7700BA0389 /* NSCharacterSet.swift in Sources */ = {isa = PBXBuildFile; fileRef = CEBA56951CDA0B7700BA0389 /* NSCharacterSet.swift */; }; + CEBA56971CDA0B7700BA0389 /* NSCharacterSet.swift in Sources */ = {isa = PBXBuildFile; fileRef = CEBA56951CDA0B7700BA0389 /* NSCharacterSet.swift */; }; + CEBA56981CDA0B7700BA0389 /* NSCharacterSet.swift in Sources */ = {isa = PBXBuildFile; fileRef = CEBA56951CDA0B7700BA0389 /* NSCharacterSet.swift */; }; + CEBA569A1CDA0B8200BA0389 /* String.swift in Sources */ = {isa = PBXBuildFile; fileRef = CEBA56991CDA0B8200BA0389 /* String.swift */; }; + CEBA569B1CDA0B8200BA0389 /* String.swift in Sources */ = {isa = PBXBuildFile; fileRef = CEBA56991CDA0B8200BA0389 /* String.swift */; }; + CEBA569C1CDA0B8200BA0389 /* String.swift in Sources */ = {isa = PBXBuildFile; fileRef = CEBA56991CDA0B8200BA0389 /* String.swift */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -195,6 +201,8 @@ 7472C65E1BCAC46E003CA70D /* SocketSideEffectTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SocketSideEffectTest.swift; sourceTree = ""; }; 74ABF7761C3991C10078C657 /* SocketIOClientSpec.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SocketIOClientSpec.swift; path = Source/SocketIOClientSpec.swift; sourceTree = ""; }; 74F124EF1BC574CF002966F4 /* SocketBasicPacketTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SocketBasicPacketTest.swift; sourceTree = ""; }; + CEBA56951CDA0B7700BA0389 /* NSCharacterSet.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = NSCharacterSet.swift; path = Source/NSCharacterSet.swift; sourceTree = ""; }; + CEBA56991CDA0B8200BA0389 /* String.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = String.swift; path = Source/String.swift; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -347,6 +355,7 @@ 5764DF7B1B51F24A004FF46E /* Source */ = { isa = PBXGroup; children = ( + CEBA569E1CDA0C0C00BA0389 /* utils */, 74171E501C10CD240062D398 /* SocketAckEmitter.swift */, 74171E511C10CD240062D398 /* SocketAckManager.swift */, 74171E521C10CD240062D398 /* SocketAnyEvent.swift */, @@ -372,6 +381,15 @@ name = Source; sourceTree = ""; }; + CEBA569E1CDA0C0C00BA0389 /* utils */ = { + isa = PBXGroup; + children = ( + CEBA56951CDA0B7700BA0389 /* NSCharacterSet.swift */, + CEBA56991CDA0B8200BA0389 /* String.swift */, + ); + name = utils; + sourceTree = ""; + }; /* End PBXGroup section */ /* Begin PBXHeadersBuildPhase section */ @@ -607,9 +625,11 @@ files = ( 740CA1221C496EF700CB98F4 /* SocketEngineWebsocket.swift in Sources */, 74171EA51C10CD240062D398 /* SocketIOClientStatus.swift in Sources */, + CEBA569A1CDA0B8200BA0389 /* String.swift in Sources */, 74171E751C10CD240062D398 /* SocketEngine.swift in Sources */, 74171E691C10CD240062D398 /* SocketAckManager.swift in Sources */, 7420CB791C49629E00956AA4 /* SocketEnginePollable.swift in Sources */, + CEBA56961CDA0B7700BA0389 /* NSCharacterSet.swift in Sources */, 74ABF7771C3991C10078C657 /* SocketIOClientSpec.swift in Sources */, 74171E871C10CD240062D398 /* SocketEngineSpec.swift in Sources */, 74171E631C10CD240062D398 /* SocketAckEmitter.swift in Sources */, @@ -664,9 +684,11 @@ files = ( 740CA1211C496EF200CB98F4 /* SocketEngineWebsocket.swift in Sources */, 7471CCEA1C39926300364B59 /* SocketIOClientSpec.swift in Sources */, + CEBA569B1CDA0B8200BA0389 /* String.swift in Sources */, 74171EA71C10CD240062D398 /* SocketIOClientStatus.swift in Sources */, 74171E771C10CD240062D398 /* SocketEngine.swift in Sources */, 7420CB7A1C49629E00956AA4 /* SocketEnginePollable.swift in Sources */, + CEBA56971CDA0B7700BA0389 /* NSCharacterSet.swift in Sources */, 74171E6B1C10CD240062D398 /* SocketAckManager.swift in Sources */, 74171E891C10CD240062D398 /* SocketEngineSpec.swift in Sources */, 74171E651C10CD240062D398 /* SocketAckEmitter.swift in Sources */, @@ -707,9 +729,11 @@ files = ( 740CA1201C496EEB00CB98F4 /* SocketEngineWebsocket.swift in Sources */, 7471CCEB1C39926C00364B59 /* SocketIOClientSpec.swift in Sources */, + CEBA569C1CDA0B8200BA0389 /* String.swift in Sources */, 74171EA91C10CD240062D398 /* SocketIOClientStatus.swift in Sources */, 74171E791C10CD240062D398 /* SocketEngine.swift in Sources */, 7420CB7B1C49629E00956AA4 /* SocketEnginePollable.swift in Sources */, + CEBA56981CDA0B7700BA0389 /* NSCharacterSet.swift in Sources */, 74171E6D1C10CD240062D398 /* SocketAckManager.swift in Sources */, 74171E8B1C10CD240062D398 /* SocketEngineSpec.swift in Sources */, 74171E671C10CD240062D398 /* SocketAckEmitter.swift in Sources */, diff --git a/Source/NSCharacterSet.swift b/Source/NSCharacterSet.swift new file mode 100644 index 0000000..bac1b1a --- /dev/null +++ b/Source/NSCharacterSet.swift @@ -0,0 +1,31 @@ +// +// NSCharacterSet.swift +// Socket.IO-Client-Swift +// +// Created by Erik Little on 9/16/15. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +extension NSCharacterSet { + class var allowedURLCharacterSet: NSCharacterSet { + return NSCharacterSet(charactersInString: "!*'();:@&=+$,/?%#[]\" {}").invertedSet + } +} \ No newline at end of file diff --git a/Source/SocketEngine.swift b/Source/SocketEngine.swift index add2f02..4f9e519 100644 --- a/Source/SocketEngine.swift +++ b/Source/SocketEngine.swift @@ -214,8 +214,8 @@ public final class SocketEngine : NSObject, SocketEnginePollable, SocketEngineWe urlWebSocket.path = socketPath urlPolling.path = socketPath - urlWebSocket.query = "transport=websocket" - urlPolling.query = "transport=polling&b64=1" + urlWebSocket.percentEncodedQuery = "transport=websocket" + urlPolling.percentEncodedQuery = "transport=polling&b64=1" if secure { urlPolling.scheme = "https" @@ -227,12 +227,15 @@ public final class SocketEngine : NSObject, SocketEnginePollable, SocketEngineWe if connectParams != nil { for (key, value) in connectParams! { - queryString += "&\(key)=\(value)" + let keyEsc = key.urlEncode()! + let valueEsc = "\(value)".urlEncode()! + + queryString += "&\(keyEsc)=\(valueEsc)" } } - urlWebSocket.query = urlWebSocket.query! + queryString - urlPolling.query = urlPolling.query! + queryString + urlWebSocket.percentEncodedQuery = urlWebSocket.percentEncodedQuery! + queryString + urlPolling.percentEncodedQuery = urlPolling.percentEncodedQuery! + queryString return (urlPolling.URL!, urlWebSocket.URL!) } diff --git a/Source/SocketEngineSpec.swift b/Source/SocketEngineSpec.swift index 58b5450..7fdd779 100644 --- a/Source/SocketEngineSpec.swift +++ b/Source/SocketEngineSpec.swift @@ -63,14 +63,14 @@ import Foundation extension SocketEngineSpec { var urlPollingWithSid: NSURL { let com = NSURLComponents(URL: urlPolling, resolvingAgainstBaseURL: false)! - com.query = com.query! + "&sid=\(sid)" + com.percentEncodedQuery = com.percentEncodedQuery! + "&sid=\(sid.urlEncode()!)" return com.URL! } var urlWebSocketWithSid: NSURL { let com = NSURLComponents(URL: urlWebSocket, resolvingAgainstBaseURL: false)! - com.query = com.query! + (sid == "" ? "" : "&sid=\(sid)") + com.percentEncodedQuery = com.percentEncodedQuery! + (sid == "" ? "" : "&sid=\(sid.urlEncode()!)") return com.URL! } diff --git a/Source/String.swift b/Source/String.swift new file mode 100644 index 0000000..a92619f --- /dev/null +++ b/Source/String.swift @@ -0,0 +1,31 @@ +// +// String.swift +// Socket.IO-Client-Swift +// +// Created by Erik Little on 9/16/15. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +extension String { + func urlEncode() -> String? { + return self.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.allowedURLCharacterSet) + } +} \ No newline at end of file From 119b479be295012d4b507aa885947a5a8d010603 Mon Sep 17 00:00:00 2001 From: Yannick Loriot Date: Wed, 4 May 2016 13:03:40 +0200 Subject: [PATCH 06/14] Minor refactoring to make the build of the query more readable --- Source/SocketEngine.swift | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/Source/SocketEngine.swift b/Source/SocketEngine.swift index 4f9e519..e06a811 100644 --- a/Source/SocketEngine.swift +++ b/Source/SocketEngine.swift @@ -214,8 +214,6 @@ public final class SocketEngine : NSObject, SocketEnginePollable, SocketEngineWe urlWebSocket.path = socketPath urlPolling.path = socketPath - urlWebSocket.percentEncodedQuery = "transport=websocket" - urlPolling.percentEncodedQuery = "transport=polling&b64=1" if secure { urlPolling.scheme = "https" @@ -234,8 +232,8 @@ public final class SocketEngine : NSObject, SocketEnginePollable, SocketEngineWe } } - urlWebSocket.percentEncodedQuery = urlWebSocket.percentEncodedQuery! + queryString - urlPolling.percentEncodedQuery = urlPolling.percentEncodedQuery! + queryString + urlWebSocket.percentEncodedQuery = "transport=websocket" + queryString + urlPolling.percentEncodedQuery = "transport=polling&b64=1" + queryString return (urlPolling.URL!, urlWebSocket.URL!) } From 2b4b5bf4070e3183bc24dd246ed0ea441cff9a64 Mon Sep 17 00:00:00 2001 From: Erik Date: Wed, 4 May 2016 09:27:08 -0400 Subject: [PATCH 07/14] move comment --- Source/SocketIOClientStatus.swift | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Source/SocketIOClientStatus.swift b/Source/SocketIOClientStatus.swift index 3d39e4a..04ea672 100644 --- a/Source/SocketIOClientStatus.swift +++ b/Source/SocketIOClientStatus.swift @@ -24,8 +24,9 @@ import Foundation +/// **NotConnected**: initial state +/// +/// **Disconnected**: connected before @objc public enum SocketIOClientStatus : Int { - // NotConnected: initial state - // Disconnected: connected before case NotConnected, Disconnected, Connecting, Connected } \ No newline at end of file From 0959dd35d72bbb8bdf3000f87aeb82c9eb77119c Mon Sep 17 00:00:00 2001 From: Erik Date: Wed, 4 May 2016 09:30:55 -0400 Subject: [PATCH 08/14] change author name --- Source/NSCharacterSet.swift | 2 +- Source/String.swift | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Source/NSCharacterSet.swift b/Source/NSCharacterSet.swift index bac1b1a..2b2a5b5 100644 --- a/Source/NSCharacterSet.swift +++ b/Source/NSCharacterSet.swift @@ -2,7 +2,7 @@ // NSCharacterSet.swift // Socket.IO-Client-Swift // -// Created by Erik Little on 9/16/15. +// Created by Yannick Loriot on 5/4/16. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal diff --git a/Source/String.swift b/Source/String.swift index a92619f..90a5f0c 100644 --- a/Source/String.swift +++ b/Source/String.swift @@ -2,7 +2,7 @@ // String.swift // Socket.IO-Client-Swift // -// Created by Erik Little on 9/16/15. +// Created by Yannick Loriot on 5/4/16. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal From 1c80cc7e4c5a67120d972baee298c4b51db8737c Mon Sep 17 00:00:00 2001 From: Erik Date: Wed, 4 May 2016 09:34:02 -0400 Subject: [PATCH 09/14] newline --- Source/NSCharacterSet.swift | 2 +- Source/String.swift | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Source/NSCharacterSet.swift b/Source/NSCharacterSet.swift index 2b2a5b5..3ccde2c 100644 --- a/Source/NSCharacterSet.swift +++ b/Source/NSCharacterSet.swift @@ -28,4 +28,4 @@ extension NSCharacterSet { class var allowedURLCharacterSet: NSCharacterSet { return NSCharacterSet(charactersInString: "!*'();:@&=+$,/?%#[]\" {}").invertedSet } -} \ No newline at end of file +} diff --git a/Source/String.swift b/Source/String.swift index 90a5f0c..cbc79ee 100644 --- a/Source/String.swift +++ b/Source/String.swift @@ -28,4 +28,4 @@ extension String { func urlEncode() -> String? { return self.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.allowedURLCharacterSet) } -} \ No newline at end of file +} From 18285f54011ddc78ee6cb1a2c4b7e6ca36ef0f6c Mon Sep 17 00:00:00 2001 From: Erik Date: Wed, 4 May 2016 09:44:01 -0400 Subject: [PATCH 10/14] small style changes --- Source/String.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Source/String.swift b/Source/String.swift index cbc79ee..0e30e8c 100644 --- a/Source/String.swift +++ b/Source/String.swift @@ -26,6 +26,6 @@ import Foundation extension String { func urlEncode() -> String? { - return self.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.allowedURLCharacterSet) + return stringByAddingPercentEncodingWithAllowedCharacters(.allowedURLCharacterSet) } } From e02ca23d14071aafb5d4237ba574e45b77d29676 Mon Sep 17 00:00:00 2001 From: Yannick Loriot Date: Wed, 4 May 2016 18:35:56 +0200 Subject: [PATCH 11/14] Add test case #361 --- SocketIO-MacTests/SocketEngineTest.swift | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/SocketIO-MacTests/SocketEngineTest.swift b/SocketIO-MacTests/SocketEngineTest.swift index 7b2388c..ec543a1 100644 --- a/SocketIO-MacTests/SocketEngineTest.swift +++ b/SocketIO-MacTests/SocketEngineTest.swift @@ -86,4 +86,20 @@ class SocketEngineTest: XCTestCase { engine.parsePollingMessage("41:42[\"stringTest\",\"lïne one\\nlīne \\rtwo\"]") waitForExpectationsWithTimeout(3, handler: nil) } + + func testEncodeURLProperly() { + engine.connectParams = [ + "created": "2016-05-04T18:31:15+0200" + ] + + XCTAssertEqual(engine.urlPolling.query, "transport=polling&b64=1&created=2016-05-04T18%3A31%3A15%2B0200") + XCTAssertEqual(engine.urlWebSocket.query, "transport=websocket&created=2016-05-04T18%3A31%3A15%2B0200") + + engine.connectParams = [ + "forbidden": "!*'();:@&=+$,/?%#[]\" {}" + ] + + XCTAssertEqual(engine.urlPolling.query, "transport=polling&b64=1&forbidden=%21%2A%27%28%29%3B%3A%40%26%3D%2B%24%2C%2F%3F%25%23%5B%5D%22%20%7B%7D") + XCTAssertEqual(engine.urlWebSocket.query, "transport=websocket&forbidden=%21%2A%27%28%29%3B%3A%40%26%3D%2B%24%2C%2F%3F%25%23%5B%5D%22%20%7B%7D") + } } From 4ea3f40ca781775c1dda871858012572307487d8 Mon Sep 17 00:00:00 2001 From: Erik Date: Thu, 5 May 2016 08:59:00 -0400 Subject: [PATCH 12/14] bump version --- README.md | 8 ++++---- Socket.IO-Client-Swift.podspec | 4 ++-- Source/SocketIOClientStatus.swift | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 5f21917..de43c9d 100644 --- a/README.md +++ b/README.md @@ -77,7 +77,7 @@ import PackageDescription let package = Package( name: "YourSocketIOProject", dependencies: [ - .Package(url: "https://github.com/socketio/socket.io-client-swift", majorVersion: 5) + .Package(url: "https://github.com/socketio/socket.io-client-swift", majorVersion: 6) ] ) ``` @@ -88,7 +88,7 @@ Carthage ----------------- Add this line to your `Cartfile`: ``` -github "socketio/socket.io-client-swift" ~> 6.1.0 # Or latest version +github "socketio/socket.io-client-swift" ~> 6.1.1 # Or latest version ``` Run `carthage update --platform ios,macosx`. @@ -102,7 +102,7 @@ source 'https://github.com/CocoaPods/Specs.git' platform :ios, '8.0' use_frameworks! -pod 'Socket.IO-Client-Swift', '~> 6.1.0' # Or latest version +pod 'Socket.IO-Client-Swift', '~> 6.1.1' # Or latest version ``` Install pods: @@ -130,7 +130,7 @@ CocoaSeeds Add this line to your `Seedfile`: ``` -github "socketio/socket.io-client-swift", "v6.1.0", :files => "Source/*.swift" # Or latest version +github "socketio/socket.io-client-swift", "v6.1.1", :files => "Source/*.swift" # Or latest version ``` Run `seed install`. diff --git a/Socket.IO-Client-Swift.podspec b/Socket.IO-Client-Swift.podspec index 52ae33e..248adc5 100644 --- a/Socket.IO-Client-Swift.podspec +++ b/Socket.IO-Client-Swift.podspec @@ -1,7 +1,7 @@ Pod::Spec.new do |s| s.name = "Socket.IO-Client-Swift" s.module_name = "SocketIOClientSwift" - s.version = "6.1.0" + s.version = "6.1.1" s.summary = "Socket.IO-client for iOS and OS X" s.description = <<-DESC Socket.IO-client for iOS and OS X. @@ -14,7 +14,7 @@ Pod::Spec.new do |s| s.ios.deployment_target = '8.0' s.osx.deployment_target = '10.10' s.tvos.deployment_target = '9.0' - s.source = { :git => "https://github.com/socketio/socket.io-client-swift.git", :tag => 'v6.1.0' } + s.source = { :git => "https://github.com/socketio/socket.io-client-swift.git", :tag => 'v6.1.1' } s.source_files = "Source/**/*.swift" s.requires_arc = true # s.dependency 'Starscream', '~> 0.9' # currently this repo includes Starscream swift files diff --git a/Source/SocketIOClientStatus.swift b/Source/SocketIOClientStatus.swift index 04ea672..0a34c2f 100644 --- a/Source/SocketIOClientStatus.swift +++ b/Source/SocketIOClientStatus.swift @@ -29,4 +29,4 @@ import Foundation /// **Disconnected**: connected before @objc public enum SocketIOClientStatus : Int { case NotConnected, Disconnected, Connecting, Connected -} \ No newline at end of file +} From 437c0880e865e44311888bcebfe33aa47cf51fbf Mon Sep 17 00:00:00 2001 From: Erik Date: Thu, 5 May 2016 13:12:05 -0400 Subject: [PATCH 13/14] don't use placeholder strings for binary --- SocketIO-MacTests/SocketBasicPacketTest.swift | 16 ++++++++++++++++ SocketIO-MacTests/SocketParserTest.swift | 9 +++++---- Source/SocketPacket.swift | 16 +++++++++------- Source/SocketParsable.swift | 5 ++--- 4 files changed, 32 insertions(+), 14 deletions(-) diff --git a/SocketIO-MacTests/SocketBasicPacketTest.swift b/SocketIO-MacTests/SocketBasicPacketTest.swift index b4b112d..1161fe3 100644 --- a/SocketIO-MacTests/SocketBasicPacketTest.swift +++ b/SocketIO-MacTests/SocketBasicPacketTest.swift @@ -145,4 +145,20 @@ class SocketBasicPacketTest: XCTestCase { XCTAssertEqual(packet.packetString, expectedSendString) XCTAssertEqual(packet.binary, [data2, data]) } + + func testBinaryStringPlaceholderInMessage() { + let engineString = "52-[\"test\",\"~~0\",{\"num\":0,\"_placeholder\":true},{\"num\":1,\"_placeholder\":true}]" + let socket = SocketIOClient(socketURL: NSURL()) + socket.setTestable() + + if case let .Right(packet) = socket.parseString(engineString) { + var packet = packet + XCTAssertEqual(packet.event, "test") + packet.addData(data) + packet.addData(data2) + XCTAssertEqual(packet.args[0] as? String, "~~0") + } else { + XCTFail() + } + } } diff --git a/SocketIO-MacTests/SocketParserTest.swift b/SocketIO-MacTests/SocketParserTest.swift index b205556..c8bea5c 100644 --- a/SocketIO-MacTests/SocketParserTest.swift +++ b/SocketIO-MacTests/SocketParserTest.swift @@ -18,9 +18,10 @@ class SocketParserTest: XCTestCase { "25[\"test\"]": ("/", ["test"], [], 5), "2[\"test\",\"~~0\"]": ("/", ["test", "~~0"], [], -1), "2/swift,[\"testArrayEmitReturn\",[\"test3\",\"test4\"]]": ("/swift", ["testArrayEmitReturn", ["test3", "test4"]], [], -1), - "51-/swift,[\"testMultipleItemsWithBufferEmitReturn\",[1,2],{\"test\":\"bob\"},25,\"polo\",{\"_placeholder\":true,\"num\":0}]": ("/swift", ["testMultipleItemsWithBufferEmitReturn", [1, 2], ["test": "bob"], 25, "polo", "~~0"], [], -1), + "51-/swift,[\"testMultipleItemsWithBufferEmitReturn\",[1,2],{\"test\":\"bob\"},25,\"polo\",{\"_placeholder\":true,\"num\":0}]": ("/swift", ["testMultipleItemsWithBufferEmitReturn", [1, 2], ["test": "bob"], 25, "polo", ["_placeholder": true, "num": 0]], [], -1), "3/swift,0[[\"test3\",\"test4\"]]": ("/swift", [["test3", "test4"]], [], 0), - "61-/swift,19[[1,2],{\"test\":\"bob\"},25,\"polo\",{\"_placeholder\":true,\"num\":0}]": ("/swift", [ [1, 2], ["test": "bob"], 25, "polo", "~~0"], [], 19), + "61-/swift,19[[1,2],{\"test\":\"bob\"},25,\"polo\",{\"_placeholder\":true,\"num\":0}]": + ("/swift", [ [1, 2], ["test": "bob"], 25, "polo", ["_placeholder": true, "num": 0]], [], 19), "4/swift,": ("/swift", [], [], -1), "0/swift": ("/swift", [], [], -1), "1/swift": ("/swift", [], [], -1), @@ -123,8 +124,8 @@ class SocketParserTest: XCTestCase { if case let .Right(packet) = packet { XCTAssertEqual(packet.type, SocketPacket.PacketType(rawValue: Int(type) ?? -1)!) XCTAssertEqual(packet.nsp, validValues.0) - XCTAssertTrue((packet.data as NSArray).isEqualToArray(validValues.1)) - XCTAssertTrue((packet.binary as NSArray).isEqualToArray(validValues.2)) + XCTAssertTrue((packet.data as NSArray).isEqualToArray(validValues.1), "\(packet.data)") + XCTAssertTrue((packet.binary as NSArray).isEqualToArray(validValues.2), "\(packet.binary)") XCTAssertEqual(packet.id, validValues.3) } else { XCTFail() diff --git a/Source/SocketPacket.swift b/Source/SocketPacket.swift index 52de38a..0de5485 100644 --- a/Source/SocketPacket.swift +++ b/Source/SocketPacket.swift @@ -187,19 +187,21 @@ struct SocketPacket { data = data.map(_fillInPlaceholders) } - // Helper method that looks for placeholder strings + // Helper method that looks for placeholders // If object is a collection it will recurse // Returns the object if it is not a placeholder string or the corresponding // binary data private func _fillInPlaceholders(object: AnyObject) -> AnyObject { switch object { - case let string as String where string["~~(\\d)"].groups() != nil: - return binary[Int(string["~~(\\d)"].groups()![1])!] case let dict as NSDictionary: - return dict.reduce(NSMutableDictionary(), combine: {cur, keyValue in - cur[keyValue.0 as! NSCopying] = _fillInPlaceholders(keyValue.1) - return cur - }) + if dict["_placeholder"] as? Bool ?? false { + return binary[dict["num"] as! Int] + } else { + return dict.reduce(NSMutableDictionary(), combine: {cur, keyValue in + cur[keyValue.0 as! NSCopying] = _fillInPlaceholders(keyValue.1) + return cur + }) + } case let arr as [AnyObject]: return arr.map(_fillInPlaceholders) default: diff --git a/Source/SocketParsable.swift b/Source/SocketParsable.swift index c74b160..80b5fa5 100644 --- a/Source/SocketParsable.swift +++ b/Source/SocketParsable.swift @@ -111,12 +111,11 @@ extension SocketParsable { } let d = message[parser.currentIndex.advancedBy(1).. Date: Thu, 5 May 2016 13:19:26 -0400 Subject: [PATCH 14/14] no longer need swiftregex --- .../project.pbxproj | 12 -- Source/SwiftRegex.swift | 195 ------------------ 2 files changed, 207 deletions(-) delete mode 100644 Source/SwiftRegex.swift diff --git a/Socket.IO-Client-Swift.xcodeproj/project.pbxproj b/Socket.IO-Client-Swift.xcodeproj/project.pbxproj index 97318d8..c373933 100644 --- a/Socket.IO-Client-Swift.xcodeproj/project.pbxproj +++ b/Socket.IO-Client-Swift.xcodeproj/project.pbxproj @@ -101,11 +101,6 @@ 74171EC51C10CD240062D398 /* SocketTypes.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E601C10CD240062D398 /* SocketTypes.swift */; }; 74171EC71C10CD240062D398 /* SocketTypes.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E601C10CD240062D398 /* SocketTypes.swift */; }; 74171EC81C10CD240062D398 /* SocketTypes.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E601C10CD240062D398 /* SocketTypes.swift */; }; - 74171EC91C10CD240062D398 /* SwiftRegex.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E611C10CD240062D398 /* SwiftRegex.swift */; }; - 74171ECA1C10CD240062D398 /* SwiftRegex.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E611C10CD240062D398 /* SwiftRegex.swift */; }; - 74171ECB1C10CD240062D398 /* SwiftRegex.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E611C10CD240062D398 /* SwiftRegex.swift */; }; - 74171ECD1C10CD240062D398 /* SwiftRegex.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E611C10CD240062D398 /* SwiftRegex.swift */; }; - 74171ECE1C10CD240062D398 /* SwiftRegex.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E611C10CD240062D398 /* SwiftRegex.swift */; }; 74171ECF1C10CD240062D398 /* WebSocket.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E621C10CD240062D398 /* WebSocket.swift */; }; 74171ED01C10CD240062D398 /* WebSocket.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E621C10CD240062D398 /* WebSocket.swift */; }; 74171ED11C10CD240062D398 /* WebSocket.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E621C10CD240062D398 /* WebSocket.swift */; }; @@ -190,7 +185,6 @@ 74171E5E1C10CD240062D398 /* SocketParsable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SocketParsable.swift; path = Source/SocketParsable.swift; sourceTree = ""; }; 74171E5F1C10CD240062D398 /* SocketStringReader.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SocketStringReader.swift; path = Source/SocketStringReader.swift; sourceTree = ""; }; 74171E601C10CD240062D398 /* SocketTypes.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SocketTypes.swift; path = Source/SocketTypes.swift; sourceTree = ""; }; - 74171E611C10CD240062D398 /* SwiftRegex.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SwiftRegex.swift; path = Source/SwiftRegex.swift; sourceTree = ""; }; 74171E621C10CD240062D398 /* WebSocket.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = WebSocket.swift; path = Source/WebSocket.swift; sourceTree = ""; }; 741F39ED1BD025D80026C9CC /* SocketEngineTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SocketEngineTest.swift; sourceTree = ""; }; 7420CB781C49629E00956AA4 /* SocketEnginePollable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SocketEnginePollable.swift; path = Source/SocketEnginePollable.swift; sourceTree = ""; }; @@ -375,7 +369,6 @@ 74171E5E1C10CD240062D398 /* SocketParsable.swift */, 74171E5F1C10CD240062D398 /* SocketStringReader.swift */, 74171E601C10CD240062D398 /* SocketTypes.swift */, - 74171E611C10CD240062D398 /* SwiftRegex.swift */, 74171E621C10CD240062D398 /* WebSocket.swift */, ); name = Source; @@ -638,7 +631,6 @@ 74171EAB1C10CD240062D398 /* SocketLogger.swift in Sources */, 74171E991C10CD240062D398 /* SocketIOClient.swift in Sources */, 74171E8D1C10CD240062D398 /* SocketEventHandler.swift in Sources */, - 74171EC91C10CD240062D398 /* SwiftRegex.swift in Sources */, 74171E7B1C10CD240062D398 /* SocketEngineClient.swift in Sources */, 74171ECF1C10CD240062D398 /* WebSocket.swift in Sources */, 74171EB11C10CD240062D398 /* SocketPacket.swift in Sources */, @@ -663,7 +655,6 @@ 74171E8E1C10CD240062D398 /* SocketEventHandler.swift in Sources */, 74171E7C1C10CD240062D398 /* SocketEngineClient.swift in Sources */, 74171E821C10CD240062D398 /* SocketEnginePacketType.swift in Sources */, - 74171ECA1C10CD240062D398 /* SwiftRegex.swift in Sources */, 74171EB21C10CD240062D398 /* SocketPacket.swift in Sources */, 741F39EE1BD025D80026C9CC /* SocketEngineTest.swift in Sources */, 74171EBE1C10CD240062D398 /* SocketStringReader.swift in Sources */, @@ -697,7 +688,6 @@ 74171EAD1C10CD240062D398 /* SocketLogger.swift in Sources */, 74171E9B1C10CD240062D398 /* SocketIOClient.swift in Sources */, 74171E8F1C10CD240062D398 /* SocketEventHandler.swift in Sources */, - 74171ECB1C10CD240062D398 /* SwiftRegex.swift in Sources */, 74171E7D1C10CD240062D398 /* SocketEngineClient.swift in Sources */, 74171ED11C10CD240062D398 /* WebSocket.swift in Sources */, 74171EB31C10CD240062D398 /* SocketPacket.swift in Sources */, @@ -742,7 +732,6 @@ 74171EAF1C10CD240062D398 /* SocketLogger.swift in Sources */, 74171E9D1C10CD240062D398 /* SocketIOClient.swift in Sources */, 74171E911C10CD240062D398 /* SocketEventHandler.swift in Sources */, - 74171ECD1C10CD240062D398 /* SwiftRegex.swift in Sources */, 74171E7F1C10CD240062D398 /* SocketEngineClient.swift in Sources */, 74171ED31C10CD240062D398 /* WebSocket.swift in Sources */, 74171EB51C10CD240062D398 /* SocketPacket.swift in Sources */, @@ -767,7 +756,6 @@ 74171E921C10CD240062D398 /* SocketEventHandler.swift in Sources */, 74171E801C10CD240062D398 /* SocketEngineClient.swift in Sources */, 74171E861C10CD240062D398 /* SocketEnginePacketType.swift in Sources */, - 74171ECE1C10CD240062D398 /* SwiftRegex.swift in Sources */, 74171EB61C10CD240062D398 /* SocketPacket.swift in Sources */, 57634A2A1BD9B46D00E19CD7 /* SocketEngineTest.swift in Sources */, 74171EC21C10CD240062D398 /* SocketStringReader.swift in Sources */, diff --git a/Source/SwiftRegex.swift b/Source/SwiftRegex.swift deleted file mode 100644 index b704afd..0000000 --- a/Source/SwiftRegex.swift +++ /dev/null @@ -1,195 +0,0 @@ -// -// SwiftRegex.swift -// SwiftRegex -// -// Created by John Holdsworth on 26/06/2014. -// Copyright (c) 2014 John Holdsworth. -// -// $Id: //depot/SwiftRegex/SwiftRegex.swift#37 $ -// -// This code is in the public domain from: -// https://github.com/johnno1962/SwiftRegex -// - -import Foundation - -infix operator <~ { associativity none precedence 130 } - -private let lock = dispatch_semaphore_create(1) -private var swiftRegexCache = [String: NSRegularExpression]() - -internal final class SwiftRegex : NSObject, BooleanType { - var target: String - var regex: NSRegularExpression - - init(target:String, pattern:String, options:NSRegularExpressionOptions?) { - self.target = target - - if dispatch_semaphore_wait(lock, dispatch_time(DISPATCH_TIME_NOW, Int64(10 * NSEC_PER_MSEC))) != 0 { - do { - let regex = try NSRegularExpression(pattern: pattern, options: - NSRegularExpressionOptions.DotMatchesLineSeparators) - self.regex = regex - } catch let error as NSError { - SwiftRegex.failure("Error in pattern: \(pattern) - \(error)") - self.regex = NSRegularExpression() - } - - super.init() - return - } - - if let regex = swiftRegexCache[pattern] { - self.regex = regex - } else { - do { - let regex = try NSRegularExpression(pattern: pattern, options: - NSRegularExpressionOptions.DotMatchesLineSeparators) - swiftRegexCache[pattern] = regex - self.regex = regex - } catch let error as NSError { - SwiftRegex.failure("Error in pattern: \(pattern) - \(error)") - self.regex = NSRegularExpression() - } - } - dispatch_semaphore_signal(lock) - super.init() - } - - private static func failure(message: String) { - fatalError("SwiftRegex: \(message)") - } - - private var targetRange: NSRange { - return NSRange(location: 0,length: target.utf16.count) - } - - private func substring(range: NSRange) -> String? { - if range.location != NSNotFound { - return (target as NSString).substringWithRange(range) - } else { - return nil - } - } - - func doesMatch(options: NSMatchingOptions!) -> Bool { - return range(options).location != NSNotFound - } - - func range(options: NSMatchingOptions) -> NSRange { - return regex.rangeOfFirstMatchInString(target as String, options: [], range: targetRange) - } - - func match(options: NSMatchingOptions) -> String? { - return substring(range(options)) - } - - func groups() -> [String]? { - return groupsForMatch(regex.firstMatchInString(target as String, options: - NSMatchingOptions.WithoutAnchoringBounds, range: targetRange)) - } - - private func groupsForMatch(match: NSTextCheckingResult?) -> [String]? { - guard let match = match else { - return nil - } - var groups = [String]() - for groupno in 0...regex.numberOfCaptureGroups { - if let group = substring(match.rangeAtIndex(groupno)) { - groups += [group] - } else { - groups += ["_"] // avoids bridging problems - } - } - return groups - } - - subscript(groupno: Int) -> String? { - get { - return groups()?[groupno] - } - - set(newValue) { - if newValue == nil { - return - } - - for match in Array(matchResults().reverse()) { - let replacement = regex.replacementStringForResult(match, - inString: target as String, offset: 0, template: newValue!) - let mut = NSMutableString(string: target) - mut.replaceCharactersInRange(match.rangeAtIndex(groupno), withString: replacement) - - target = mut as String - } - } - } - - func matchResults() -> [NSTextCheckingResult] { - let matches = regex.matchesInString(target as String, options: - NSMatchingOptions.WithoutAnchoringBounds, range: targetRange) - as [NSTextCheckingResult] - - return matches - } - - func ranges() -> [NSRange] { - return matchResults().map { $0.range } - } - - func matches() -> [String] { - return matchResults().map( { self.substring($0.range)!}) - } - - func allGroups() -> [[String]?] { - return matchResults().map { self.groupsForMatch($0) } - } - - func dictionary(options: NSMatchingOptions!) -> Dictionary { - var out = Dictionary() - for match in matchResults() { - out[substring(match.rangeAtIndex(1))!] = substring(match.rangeAtIndex(2))! - } - return out - } - - func substituteMatches(substitution: ((NSTextCheckingResult, UnsafeMutablePointer) -> String), - options:NSMatchingOptions) -> String { - let out = NSMutableString() - var pos = 0 - - regex.enumerateMatchesInString(target as String, options: options, range: targetRange ) {match, flags, stop in - let matchRange = match!.range - out.appendString( self.substring(NSRange(location:pos, length:matchRange.location-pos))!) - out.appendString( substitution(match!, stop) ) - pos = matchRange.location + matchRange.length - } - - out.appendString(substring(NSRange(location:pos, length:targetRange.length-pos))!) - - return out as String - } - - var boolValue: Bool { - return doesMatch(nil) - } -} - -extension String { - subscript(pattern: String, options: NSRegularExpressionOptions) -> SwiftRegex { - return SwiftRegex(target: self, pattern: pattern, options: options) - } -} - -extension String { - subscript(pattern: String) -> SwiftRegex { - return SwiftRegex(target: self, pattern: pattern, options: nil) - } -} - -func <~ (left: SwiftRegex, right: String) -> String { - return left.substituteMatches({match, stop in - return left.regex.replacementStringForResult( match, - inString: left.target as String, offset: 0, template: right ) - }, options: []) -}