websocket and user center
This commit is contained in:
@@ -0,0 +1,250 @@
|
||||
//
|
||||
// SocketPacket.swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Erik Little on 1/18/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
|
||||
|
||||
/// A struct that represents a socket.io packet.
|
||||
public struct SocketPacket : CustomStringConvertible {
|
||||
// MARK: Properties
|
||||
|
||||
private static let logType = "SocketPacket"
|
||||
|
||||
/// The namespace for this packet.
|
||||
public let nsp: String
|
||||
|
||||
/// If > 0 then this packet is using acking.
|
||||
public let id: Int
|
||||
|
||||
/// The type of this packet.
|
||||
public let type: PacketType
|
||||
|
||||
/// An array of binary data for this packet.
|
||||
public internal(set) var binary: [Data]
|
||||
|
||||
/// The data for this event.
|
||||
///
|
||||
/// Note: This includes all data inside of the socket.io packet payload array, which includes the event name for
|
||||
/// event type packets.
|
||||
public internal(set) var data: [Any]
|
||||
|
||||
/// Returns the payload for this packet, minus the event name if this is an event or binaryEvent type packet.
|
||||
public var args: [Any] {
|
||||
if type == .event || type == .binaryEvent && data.count != 0 {
|
||||
return Array(data.dropFirst())
|
||||
} else {
|
||||
return data
|
||||
}
|
||||
}
|
||||
|
||||
private let placeholders: Int
|
||||
|
||||
/// A string representation of this packet.
|
||||
public var description: String {
|
||||
return "SocketPacket {type: \(String(type.rawValue)); data: " +
|
||||
"\(String(describing: data)); id: \(id); placeholders: \(placeholders); nsp: \(nsp)}"
|
||||
}
|
||||
|
||||
/// The event name for this packet.
|
||||
public var event: String {
|
||||
return String(describing: data[0])
|
||||
}
|
||||
|
||||
/// A string representation of this packet.
|
||||
public var packetString: String {
|
||||
return createPacketString()
|
||||
}
|
||||
|
||||
init(type: PacketType, data: [Any] = [Any](), id: Int = -1, nsp: String, placeholders: Int = 0,
|
||||
binary: [Data] = [Data]()) {
|
||||
self.data = data
|
||||
self.id = id
|
||||
self.nsp = nsp
|
||||
self.type = type
|
||||
self.placeholders = placeholders
|
||||
self.binary = binary
|
||||
}
|
||||
|
||||
mutating func addData(_ data: Data) -> Bool {
|
||||
if placeholders == binary.count {
|
||||
return true
|
||||
}
|
||||
|
||||
binary.append(data)
|
||||
|
||||
if placeholders == binary.count {
|
||||
fillInPlaceholders()
|
||||
return true
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
private func completeMessage(_ message: String) -> String {
|
||||
guard data.count != 0 else { return message + "[]" }
|
||||
guard let jsonSend = try? data.toJSON(), let jsonString = String(data: jsonSend, encoding: .utf8) else {
|
||||
DefaultSocketLogger.Logger.error("Error creating JSON object in SocketPacket.completeMessage",
|
||||
type: SocketPacket.logType)
|
||||
|
||||
return message + "[]"
|
||||
}
|
||||
|
||||
return message + jsonString
|
||||
}
|
||||
|
||||
private func createPacketString() -> String {
|
||||
let typeString = String(type.rawValue)
|
||||
// Binary count?
|
||||
let binaryCountString = typeString + (type.isBinary ? "\(String(binary.count))-" : "")
|
||||
// Namespace?
|
||||
let nspString = binaryCountString + (nsp != "/" ? "\(nsp)," : "")
|
||||
// Ack number?
|
||||
let idString = nspString + (id != -1 ? String(id) : "")
|
||||
|
||||
return completeMessage(idString)
|
||||
}
|
||||
|
||||
// Called when we have all the binary data for a packet
|
||||
// calls _fillInPlaceholders, which replaces placeholders with the
|
||||
// corresponding binary
|
||||
private mutating func fillInPlaceholders() {
|
||||
data = data.map(_fillInPlaceholders)
|
||||
}
|
||||
|
||||
// Helper method that looks for placeholders
|
||||
// If object is a collection it will recurse
|
||||
// Returns the object if it is not a placeholder or the corresponding
|
||||
// binary data
|
||||
private func _fillInPlaceholders(_ object: Any) -> Any {
|
||||
switch object {
|
||||
case let dict as JSON:
|
||||
if dict["_placeholder"] as? Bool ?? false {
|
||||
return binary[dict["num"] as! Int]
|
||||
} else {
|
||||
return dict.reduce(into: JSON(), {cur, keyValue in
|
||||
cur[keyValue.0] = _fillInPlaceholders(keyValue.1)
|
||||
})
|
||||
}
|
||||
case let arr as [Any]:
|
||||
return arr.map(_fillInPlaceholders)
|
||||
default:
|
||||
return object
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public extension SocketPacket {
|
||||
// MARK: PacketType enum
|
||||
|
||||
/// The type of packets.
|
||||
public enum PacketType: Int {
|
||||
// MARK: Cases
|
||||
|
||||
/// Connect: 0
|
||||
case connect
|
||||
|
||||
/// Disconnect: 1
|
||||
case disconnect
|
||||
|
||||
/// Event: 2
|
||||
case event
|
||||
|
||||
/// Ack: 3
|
||||
case ack
|
||||
|
||||
/// Error: 4
|
||||
case error
|
||||
|
||||
/// Binary Event: 5
|
||||
case binaryEvent
|
||||
|
||||
/// Binary Ack: 6
|
||||
case binaryAck
|
||||
|
||||
// MARK: Properties
|
||||
|
||||
/// Whether or not this type is binary
|
||||
public var isBinary: Bool {
|
||||
return self == .binaryAck || self == .binaryEvent
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension SocketPacket {
|
||||
private static func findType(_ binCount: Int, ack: Bool) -> PacketType {
|
||||
switch binCount {
|
||||
case 0 where !ack:
|
||||
return .event
|
||||
case 0 where ack:
|
||||
return .ack
|
||||
case _ where !ack:
|
||||
return .binaryEvent
|
||||
case _ where ack:
|
||||
return .binaryAck
|
||||
default:
|
||||
return .error
|
||||
}
|
||||
}
|
||||
|
||||
static func packetFromEmit(_ items: [Any], id: Int, nsp: String, ack: Bool, checkForBinary: Bool = true) -> SocketPacket {
|
||||
if checkForBinary {
|
||||
let (parsedData, binary) = deconstructData(items)
|
||||
|
||||
return SocketPacket(type: findType(binary.count, ack: ack), data: parsedData, id: id, nsp: nsp,
|
||||
binary: binary)
|
||||
} else {
|
||||
return SocketPacket(type: findType(0, ack: ack), data: items, id: id, nsp: nsp)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension SocketPacket {
|
||||
// Recursive function that looks for NSData in collections
|
||||
static func shred(_ data: Any, binary: inout [Data]) -> Any {
|
||||
let placeholder = ["_placeholder": true, "num": binary.count] as JSON
|
||||
|
||||
switch data {
|
||||
case let bin as Data:
|
||||
binary.append(bin)
|
||||
|
||||
return placeholder
|
||||
case let arr as [Any]:
|
||||
return arr.map({shred($0, binary: &binary)})
|
||||
case let dict as JSON:
|
||||
return dict.reduce(into: JSON(), {cur, keyValue in
|
||||
cur[keyValue.0] = shred(keyValue.1, binary: &binary)
|
||||
})
|
||||
default:
|
||||
return data
|
||||
}
|
||||
}
|
||||
|
||||
// Removes binary data from emit data
|
||||
// Returns a type containing the de-binaryed data and the binary
|
||||
static func deconstructData(_ data: [Any]) -> ([Any], [Data]) {
|
||||
var binary = [Data]()
|
||||
|
||||
return (data.map({ shred($0, binary: &binary) }), binary)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
//
|
||||
// SocketParsable.swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// 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
|
||||
|
||||
/// Defines that a type will be able to parse socket.io-protocol messages.
|
||||
public protocol SocketParsable : AnyObject {
|
||||
// MARK: Methods
|
||||
|
||||
/// Called when the engine has received some binary data that should be attached to a packet.
|
||||
///
|
||||
/// Packets binary data should be sent directly after the packet that expects it, so there's confusion over
|
||||
/// where the data should go. Data should be received in the order it is sent, so that the correct data is put
|
||||
/// into the correct placeholder.
|
||||
///
|
||||
/// - parameter data: The data that should be attached to a packet.
|
||||
func parseBinaryData(_ data: Data) -> SocketPacket?
|
||||
|
||||
/// Called when the engine has received a string that should be parsed into a socket.io packet.
|
||||
///
|
||||
/// - parameter message: The string that needs parsing.
|
||||
/// - returns: A completed socket packet if there is no more data left to collect.
|
||||
func parseSocketMessage(_ message: String) -> SocketPacket?
|
||||
}
|
||||
|
||||
/// Errors that can be thrown during parsing.
|
||||
public enum SocketParsableError : Error {
|
||||
// MARK: Cases
|
||||
|
||||
/// Thrown when a packet received has an invalid data array, or is missing the data array.
|
||||
case invalidDataArray
|
||||
|
||||
/// Thrown when an malformed packet is received.
|
||||
case invalidPacket
|
||||
|
||||
/// Thrown when the parser receives an unknown packet type.
|
||||
case invalidPacketType
|
||||
}
|
||||
|
||||
/// Says that a type will be able to buffer binary data before all data for an event has come in.
|
||||
public protocol SocketDataBufferable : AnyObject {
|
||||
// MARK: Properties
|
||||
|
||||
/// A list of packets that are waiting for binary data.
|
||||
///
|
||||
/// The way that socket.io works all data should be sent directly after each packet.
|
||||
/// So this should ideally be an array of one packet waiting for data.
|
||||
///
|
||||
/// **This should not be modified directly.**
|
||||
var waitingPackets: [SocketPacket] { get set }
|
||||
}
|
||||
|
||||
public extension SocketParsable where Self: SocketManagerSpec & SocketDataBufferable {
|
||||
/// Parses a message from the engine, returning a complete SocketPacket or throwing.
|
||||
///
|
||||
/// - parameter message: The message to parse.
|
||||
/// - returns: A completed packet, or throwing.
|
||||
internal func parseString(_ message: String) throws -> SocketPacket {
|
||||
var reader = SocketStringReader(message: message)
|
||||
|
||||
guard let type = Int(reader.read(count: 1)).flatMap({ SocketPacket.PacketType(rawValue: $0) }) else {
|
||||
throw SocketParsableError.invalidPacketType
|
||||
}
|
||||
|
||||
if !reader.hasNext {
|
||||
return SocketPacket(type: type, nsp: "/")
|
||||
}
|
||||
|
||||
var namespace = "/"
|
||||
var placeholders = -1
|
||||
|
||||
if type.isBinary {
|
||||
if let holders = Int(reader.readUntilOccurence(of: "-")) {
|
||||
placeholders = holders
|
||||
} else {
|
||||
throw SocketParsableError.invalidPacket
|
||||
}
|
||||
}
|
||||
|
||||
if reader.currentCharacter == "/" {
|
||||
namespace = reader.readUntilOccurence(of: ",")
|
||||
}
|
||||
|
||||
if !reader.hasNext {
|
||||
return SocketPacket(type: type, nsp: namespace, placeholders: placeholders)
|
||||
}
|
||||
|
||||
var idString = ""
|
||||
|
||||
if type == .error {
|
||||
reader.advance(by: -1)
|
||||
} else {
|
||||
while reader.hasNext {
|
||||
if let int = Int(reader.read(count: 1)) {
|
||||
idString += String(int)
|
||||
} else {
|
||||
reader.advance(by: -2)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var dataArray = String(message.utf16[message.utf16.index(reader.currentIndex, offsetBy: 1)...])!
|
||||
|
||||
if type == .error && !dataArray.hasPrefix("[") && !dataArray.hasSuffix("]") {
|
||||
dataArray = "[" + dataArray + "]"
|
||||
}
|
||||
|
||||
let data = try parseData(dataArray)
|
||||
|
||||
return SocketPacket(type: type, data: data, id: Int(idString) ?? -1, nsp: namespace, placeholders: placeholders)
|
||||
}
|
||||
|
||||
// Parses data for events
|
||||
private func parseData(_ data: String) throws -> [Any] {
|
||||
do {
|
||||
return try data.toArray()
|
||||
} catch {
|
||||
throw SocketParsableError.invalidDataArray
|
||||
}
|
||||
}
|
||||
|
||||
/// Called when the engine has received a string that should be parsed into a socket.io packet.
|
||||
///
|
||||
/// - parameter message: The string that needs parsing.
|
||||
/// - returns: A completed socket packet or nil if the packet is invalid.
|
||||
public func parseSocketMessage(_ message: String) -> SocketPacket? {
|
||||
guard !message.isEmpty else { return nil }
|
||||
|
||||
DefaultSocketLogger.Logger.log("Parsing \(message)", type: "SocketParser")
|
||||
|
||||
do {
|
||||
let packet = try parseString(message)
|
||||
|
||||
DefaultSocketLogger.Logger.log("Decoded packet as: \(packet.description)", type: "SocketParser")
|
||||
|
||||
return packet
|
||||
} catch {
|
||||
DefaultSocketLogger.Logger.error("\(error): \(message)", type: "SocketParser")
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
/// Called when the engine has received some binary data that should be attached to a packet.
|
||||
///
|
||||
/// Packets binary data should be sent directly after the packet that expects it, so there's confusion over
|
||||
/// where the data should go. Data should be received in the order it is sent, so that the correct data is put
|
||||
/// into the correct placeholder.
|
||||
///
|
||||
/// - parameter data: The data that should be attached to a packet.
|
||||
/// - returns: A completed socket packet if there is no more data left to collect.
|
||||
public func parseBinaryData(_ data: Data) -> SocketPacket? {
|
||||
guard !waitingPackets.isEmpty else {
|
||||
DefaultSocketLogger.Logger.error("Got data when not remaking packet", type: "SocketParser")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Should execute event?
|
||||
guard waitingPackets[waitingPackets.count - 1].addData(data) else { return nil }
|
||||
|
||||
return waitingPackets.removeLast()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user