SocketPacket.swift 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. //
  2. // SocketPacket.swift
  3. // Socket.IO-Client-Swift
  4. //
  5. // Created by Erik Little on 1/18/15.
  6. //
  7. // Permission is hereby granted, free of charge, to any person obtaining a copy
  8. // of this software and associated documentation files (the "Software"), to deal
  9. // in the Software without restriction, including without limitation the rights
  10. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. // copies of the Software, and to permit persons to whom the Software is
  12. // furnished to do so, subject to the following conditions:
  13. //
  14. // The above copyright notice and this permission notice shall be included in
  15. // all copies or substantial portions of the Software.
  16. //
  17. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  23. // THE SOFTWARE.
  24. //
  25. import Foundation
  26. struct SocketPacket {
  27. private let placeholders: Int
  28. private static let logType = "SocketPacket"
  29. let nsp: String
  30. let id: Int
  31. let type: PacketType
  32. enum PacketType: Int {
  33. case Connect, Disconnect, Event, Ack, Error, BinaryEvent, BinaryAck
  34. }
  35. var args: [AnyObject] {
  36. if type == .Event || type == .BinaryEvent && data.count != 0 {
  37. return Array(data.dropFirst())
  38. } else {
  39. return data
  40. }
  41. }
  42. var binary: [NSData]
  43. var data: [AnyObject]
  44. var description: String {
  45. return "SocketPacket {type: \(String(type.rawValue)); data: " +
  46. "\(String(data)); id: \(id); placeholders: \(placeholders); nsp: \(nsp)}"
  47. }
  48. var event: String {
  49. return String(data[0])
  50. }
  51. var packetString: String {
  52. return createPacketString()
  53. }
  54. init(type: PacketType, data: [AnyObject] = [AnyObject](), id: Int = -1,
  55. nsp: String, placeholders: Int = 0, binary: [NSData] = [NSData]()) {
  56. self.data = data
  57. self.id = id
  58. self.nsp = nsp
  59. self.type = type
  60. self.placeholders = placeholders
  61. self.binary = binary
  62. }
  63. mutating func addData(data: NSData) -> Bool {
  64. if placeholders == binary.count {
  65. return true
  66. }
  67. binary.append(data)
  68. if placeholders == binary.count {
  69. fillInPlaceholders()
  70. return true
  71. } else {
  72. return false
  73. }
  74. }
  75. private func completeMessage(message: String) -> String {
  76. let restOfMessage: String
  77. if data.count == 0 {
  78. return message + "[]"
  79. }
  80. do {
  81. let jsonSend = try NSJSONSerialization.dataWithJSONObject(data,
  82. options: NSJSONWritingOptions(rawValue: 0))
  83. guard let jsonString = String(data: jsonSend, encoding: NSUTF8StringEncoding) else {
  84. return message + "[]"
  85. }
  86. restOfMessage = jsonString
  87. } catch {
  88. DefaultSocketLogger.Logger.error("Error creating JSON object in SocketPacket.completeMessage",
  89. type: SocketPacket.logType)
  90. restOfMessage = "[]"
  91. }
  92. return message + restOfMessage
  93. }
  94. private func createAck() -> String {
  95. let message: String
  96. if type == .Ack {
  97. if nsp == "/" {
  98. message = "3\(id)"
  99. } else {
  100. message = "3\(nsp),\(id)"
  101. }
  102. } else {
  103. if nsp == "/" {
  104. message = "6\(binary.count)-\(id)"
  105. } else {
  106. message = "6\(binary.count)-\(nsp),\(id)"
  107. }
  108. }
  109. return completeMessage(message)
  110. }
  111. private func createMessageForEvent() -> String {
  112. let message: String
  113. if type == .Event {
  114. if nsp == "/" {
  115. if id == -1 {
  116. message = "2"
  117. } else {
  118. message = "2\(id)"
  119. }
  120. } else {
  121. if id == -1 {
  122. message = "2\(nsp),"
  123. } else {
  124. message = "2\(nsp),\(id)"
  125. }
  126. }
  127. } else {
  128. if nsp == "/" {
  129. if id == -1 {
  130. message = "5\(binary.count)-"
  131. } else {
  132. message = "5\(binary.count)-\(id)"
  133. }
  134. } else {
  135. if id == -1 {
  136. message = "5\(binary.count)-\(nsp),"
  137. } else {
  138. message = "5\(binary.count)-\(nsp),\(id)"
  139. }
  140. }
  141. }
  142. return completeMessage(message)
  143. }
  144. private func createPacketString() -> String {
  145. let str: String
  146. if type == .Event || type == .BinaryEvent {
  147. str = createMessageForEvent()
  148. } else {
  149. str = createAck()
  150. }
  151. return str
  152. }
  153. // Called when we have all the binary data for a packet
  154. // calls _fillInPlaceholders, which replaces placeholders with the
  155. // corresponding binary
  156. private mutating func fillInPlaceholders() {
  157. data = data.map(_fillInPlaceholders)
  158. }
  159. // Helper method that looks for placeholders
  160. // If object is a collection it will recurse
  161. // Returns the object if it is not a placeholder or the corresponding
  162. // binary data
  163. private func _fillInPlaceholders(object: AnyObject) -> AnyObject {
  164. switch object {
  165. case let dict as NSDictionary:
  166. if dict["_placeholder"] as? Bool ?? false {
  167. return binary[dict["num"] as! Int]
  168. } else {
  169. return dict.reduce(NSMutableDictionary(), combine: {cur, keyValue in
  170. cur[keyValue.0 as! NSCopying] = _fillInPlaceholders(keyValue.1)
  171. return cur
  172. })
  173. }
  174. case let arr as [AnyObject]:
  175. return arr.map(_fillInPlaceholders)
  176. default:
  177. return object
  178. }
  179. }
  180. }
  181. extension SocketPacket {
  182. private static func findType(binCount: Int, ack: Bool) -> PacketType {
  183. switch binCount {
  184. case 0 where !ack:
  185. return .Event
  186. case 0 where ack:
  187. return .Ack
  188. case _ where !ack:
  189. return .BinaryEvent
  190. case _ where ack:
  191. return .BinaryAck
  192. default:
  193. return .Error
  194. }
  195. }
  196. static func packetFromEmit(items: [AnyObject], id: Int, nsp: String, ack: Bool) -> SocketPacket {
  197. let (parsedData, binary) = deconstructData(items)
  198. let packet = SocketPacket(type: findType(binary.count, ack: ack), data: parsedData,
  199. id: id, nsp: nsp, binary: binary)
  200. return packet
  201. }
  202. }
  203. private extension SocketPacket {
  204. // Recursive function that looks for NSData in collections
  205. static func shred(data: AnyObject, inout binary: [NSData]) -> AnyObject {
  206. let placeholder = ["_placeholder": true, "num": binary.count]
  207. switch data {
  208. case let bin as NSData:
  209. binary.append(bin)
  210. return placeholder
  211. case let arr as [AnyObject]:
  212. return arr.map({shred($0, binary: &binary)})
  213. case let dict as NSDictionary:
  214. return dict.reduce(NSMutableDictionary(), combine: {cur, keyValue in
  215. cur[keyValue.0 as! NSCopying] = shred(keyValue.1, binary: &binary)
  216. return cur
  217. })
  218. default:
  219. return data
  220. }
  221. }
  222. // Removes binary data from emit data
  223. // Returns a type containing the de-binaryed data and the binary
  224. static func deconstructData(data: [AnyObject]) -> ([AnyObject], [NSData]) {
  225. var binary = [NSData]()
  226. return (data.map({shred($0, binary: &binary)}), binary)
  227. }
  228. }