You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

262 lines
9.1 KiB

2 years ago
  1. //
  2. // SocketEnginePollable.swift
  3. // Socket.IO-Client-Swift
  4. //
  5. // Created by Erik Little on 1/15/16.
  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. import Foundation
  25. /// Protocol that is used to implement socket.io polling support
  26. public protocol SocketEnginePollable: SocketEngineSpec {
  27. // MARK: Properties
  28. /// `true` If engine's session has been invalidated.
  29. var invalidated: Bool { get }
  30. /// A queue of engine.io messages waiting for POSTing
  31. ///
  32. /// **You should not touch this directly**
  33. var postWait: [Post] { get set }
  34. /// The URLSession that will be used for polling.
  35. var session: URLSession? { get }
  36. /// `true` if there is an outstanding poll. Trying to poll before the first is done will cause socket.io to
  37. /// disconnect us.
  38. ///
  39. /// **Do not touch this directly**
  40. var waitingForPoll: Bool { get set }
  41. /// `true` if there is an outstanding post. Trying to post before the first is done will cause socket.io to
  42. /// disconnect us.
  43. ///
  44. /// **Do not touch this directly**
  45. var waitingForPost: Bool { get set }
  46. // MARK: Methods
  47. /// Call to send a long-polling request.
  48. ///
  49. /// You shouldn't need to call this directly, the engine should automatically maintain a long-poll request.
  50. func doPoll()
  51. /// Sends an engine.io message through the polling transport.
  52. ///
  53. /// You shouldn't call this directly, instead call the `write` method on `SocketEngine`.
  54. ///
  55. /// - parameter message: The message to send.
  56. /// - parameter withType: The type of message to send.
  57. /// - parameter withData: The data associated with this message.
  58. func sendPollMessage(_ message: String, withType type: SocketEnginePacketType, withData datas: [Data], completion: (() -> ())?)
  59. /// Call to stop polling and invalidate the URLSession.
  60. func stopPolling()
  61. }
  62. // Default polling methods
  63. extension SocketEnginePollable {
  64. func createRequestForPostWithPostWait() -> URLRequest {
  65. defer {
  66. for packet in postWait { packet.completion?() }
  67. postWait.removeAll(keepingCapacity: true)
  68. }
  69. var postStr = ""
  70. if version.rawValue >= 3 {
  71. postStr = postWait.lazy.map({ $0.msg }).joined(separator: "\u{1e}")
  72. } else {
  73. for packet in postWait {
  74. postStr += "\(packet.msg.utf16.count):\(packet.msg)"
  75. }
  76. }
  77. DefaultSocketLogger.Logger.log("Created POST string: \(postStr)", type: "SocketEnginePolling")
  78. var req = URLRequest(url: urlPollingWithSid)
  79. let postData = postStr.data(using: .utf8, allowLossyConversion: false)!
  80. addHeaders(to: &req)
  81. req.httpMethod = "POST"
  82. req.setValue("text/plain; charset=UTF-8", forHTTPHeaderField: "Content-Type")
  83. req.httpBody = postData
  84. req.setValue(String(postData.count), forHTTPHeaderField: "Content-Length")
  85. return req
  86. }
  87. /// Call to send a long-polling request.
  88. ///
  89. /// You shouldn't need to call this directly, the engine should automatically maintain a long-poll request.
  90. public func doPoll() {
  91. guard polling && !waitingForPoll && connected && !closed else { return }
  92. var req = URLRequest(url: urlPollingWithSid)
  93. addHeaders(to: &req)
  94. doLongPoll(for: req)
  95. }
  96. func doRequest(for req: URLRequest, callbackWith callback: @escaping (Data?, URLResponse?, Error?) -> ()) {
  97. guard polling && !closed && !invalidated && !fastUpgrade else { return }
  98. DefaultSocketLogger.Logger.log("Doing polling \(req.httpMethod ?? "") \(req)", type: "SocketEnginePolling")
  99. session?.dataTask(with: req, completionHandler: callback).resume()
  100. }
  101. func doLongPoll(for req: URLRequest) {
  102. waitingForPoll = true
  103. doRequest(for: req) {[weak self] data, res, err in
  104. guard let this = self, this.polling else { return }
  105. guard let data = data, let res = res as? HTTPURLResponse, res.statusCode == 200 else {
  106. if let err = err {
  107. DefaultSocketLogger.Logger.error(err.localizedDescription, type: "SocketEnginePolling")
  108. } else {
  109. DefaultSocketLogger.Logger.error("Error during long poll request", type: "SocketEnginePolling")
  110. }
  111. if this.polling {
  112. this.didError(reason: err?.localizedDescription ?? "Error")
  113. }
  114. return
  115. }
  116. DefaultSocketLogger.Logger.log("Got polling response", type: "SocketEnginePolling")
  117. if let str = String(data: data, encoding: .utf8) {
  118. this.parsePollingMessage(str)
  119. }
  120. this.waitingForPoll = false
  121. if this.fastUpgrade {
  122. this.doFastUpgrade()
  123. } else if !this.closed && this.polling {
  124. this.doPoll()
  125. }
  126. }
  127. }
  128. private func flushWaitingForPost() {
  129. guard postWait.count != 0 && connected else { return }
  130. guard polling else {
  131. flushWaitingForPostToWebSocket()
  132. return
  133. }
  134. let req = createRequestForPostWithPostWait()
  135. waitingForPost = true
  136. DefaultSocketLogger.Logger.log("POSTing", type: "SocketEnginePolling")
  137. doRequest(for: req) {[weak self] _, res, err in
  138. guard let this = self else { return }
  139. guard let res = res as? HTTPURLResponse, res.statusCode == 200 else {
  140. if let err = err {
  141. DefaultSocketLogger.Logger.error(err.localizedDescription, type: "SocketEnginePolling")
  142. } else {
  143. DefaultSocketLogger.Logger.error("Error flushing waiting posts", type: "SocketEnginePolling")
  144. }
  145. if this.polling {
  146. this.didError(reason: err?.localizedDescription ?? "Error")
  147. }
  148. return
  149. }
  150. this.waitingForPost = false
  151. if !this.fastUpgrade {
  152. this.flushWaitingForPost()
  153. this.doPoll()
  154. }
  155. }
  156. }
  157. func parsePollingMessage(_ str: String) {
  158. guard !str.isEmpty else { return }
  159. DefaultSocketLogger.Logger.log("Got poll message: \(str)", type: "SocketEnginePolling")
  160. if version.rawValue >= 3 {
  161. let records = str.components(separatedBy: "\u{1e}")
  162. for record in records {
  163. parseEngineMessage(record)
  164. }
  165. } else {
  166. guard str.count != 1 else {
  167. parseEngineMessage(str)
  168. return
  169. }
  170. var reader = SocketStringReader(message: str)
  171. while reader.hasNext {
  172. if let n = Int(reader.readUntilOccurence(of: ":")) {
  173. parseEngineMessage(reader.read(count: n))
  174. } else {
  175. parseEngineMessage(str)
  176. break
  177. }
  178. }
  179. }
  180. }
  181. /// Sends an engine.io message through the polling transport.
  182. ///
  183. /// You shouldn't call this directly, instead call the `write` method on `SocketEngine`.
  184. ///
  185. /// - parameter message: The message to send.
  186. /// - parameter withType: The type of message to send.
  187. /// - parameter withData: The data associated with this message.
  188. /// - parameter completion: Callback called on transport write completion.
  189. public func sendPollMessage(_ message: String, withType type: SocketEnginePacketType, withData datas: [Data], completion: (() -> ())? = nil) {
  190. DefaultSocketLogger.Logger.log("Sending poll: \(message) as type: \(type.rawValue)", type: "SocketEnginePolling")
  191. postWait.append((String(type.rawValue) + message, completion))
  192. for data in datas {
  193. if case let .right(bin) = createBinaryDataForSend(using: data) {
  194. postWait.append((bin, {}))
  195. }
  196. }
  197. if !waitingForPost {
  198. flushWaitingForPost()
  199. }
  200. }
  201. /// Call to stop polling and invalidate the URLSession.
  202. public func stopPolling() {
  203. waitingForPoll = false
  204. waitingForPost = false
  205. session?.finishTasksAndInvalidate()
  206. }
  207. }