diff --git a/Podfile b/Podfile
index ab4c19f8a..dfa6fb109 100644
--- a/Podfile
+++ b/Podfile
@@ -27,7 +27,6 @@ abstract_target 'iMastShared' do
target 'iMast' do
# Pods for iMast
pod 'Crossroad', '~> 3.0.1'
- pod 'Starscream', '~> 3.1.1'
pod 'ReachabilitySwift', '~> 4.3.1'
pod 'Eureka', '~> 5.1'
pod 'EurekaFormBuilder', '~> 0.2.0'
diff --git a/Podfile.lock b/Podfile.lock
index 3d031496d..47b1561e1 100644
--- a/Podfile.lock
+++ b/Podfile.lock
@@ -37,7 +37,6 @@ PODS:
- libwebp (~> 1.0)
- SDWebImage/Core (~> 5.0)
- SnapKit (5.0.1)
- - Starscream (3.1.1)
- SVProgressHUD (2.2.5)
- SwiftLint (0.37.0)
- SwiftyJSON (5.0.0)
@@ -65,7 +64,6 @@ DEPENDENCIES:
- SDWebImage (~> 5.3.2)
- SDWebImageWebPCoder (~> 0.2.5)
- SnapKit (~> 5.0.1)
- - Starscream (~> 3.1.1)
- SVProgressHUD
- SwiftLint (~> 0.37.0)
- SwiftyJSON (~> 5.0.0)
@@ -93,7 +91,6 @@ SPEC REPOS:
- SDWebImage
- SDWebImageWebPCoder
- SnapKit
- - Starscream
- SVProgressHUD
- SwiftLint
- SwiftyJSON
@@ -131,13 +128,12 @@ SPEC CHECKSUMS:
SDWebImage: 6ac2eb96571bff96ecde31a987172c5934a0eb7d
SDWebImageWebPCoder: 947093edd1349d820c40afbd9f42acb6cdecd987
SnapKit: 97b92857e3df3a0c71833cce143274bf6ef8e5eb
- Starscream: 4bb2f9942274833f7b4d296a55504dcfc7edb7b0
SVProgressHUD: 1428aafac632c1f86f62aa4243ec12008d7a51d6
SwiftLint: c078a14d7d7ade75e5507795d185e3da41d844d2
SwiftyJSON: 36413e04c44ee145039d332b4f4e2d3e8d6c4db7
XCGLogger: 0434f15e3909cdc450bb63faf638b8792ab782ab
"※ikemen": da47fe6e0acfbe241611221f4d98ade266bf50a2
-PODFILE CHECKSUM: 046c4bdcca7f7928751b8b3f5ffa4f10d870b57c
+PODFILE CHECKSUM: 1291a9fb9a38dad198546d1788ed410afbbf1f4c
COCOAPODS: 1.8.3
diff --git a/Sources/iOS/App/Settings.bundle/com.mono0926.LicensePlist.latest_result.txt b/Sources/iOS/App/Settings.bundle/com.mono0926.LicensePlist.latest_result.txt
index dbdaf912d..1191e1608 100644
--- a/Sources/iOS/App/Settings.bundle/com.mono0926.LicensePlist.latest_result.txt
+++ b/Sources/iOS/App/Settings.bundle/com.mono0926.LicensePlist.latest_result.txt
@@ -422,10 +422,6 @@ name: SnapKit, nameSpecified:
body: Copyright (c) 2011-P…
version: 5.0.1
-name: Starscream, nameSpecified:
-body: …
-version: 3.1.1
-
name: SVProgressHUD, nameSpecified:
body: MIT License
diff --git a/Sources/iOS/App/Settings.bundle/com.mono0926.LicensePlist.plist b/Sources/iOS/App/Settings.bundle/com.mono0926.LicensePlist.plist
index 03eeb9374..7cc91a0d9 100644
--- a/Sources/iOS/App/Settings.bundle/com.mono0926.LicensePlist.plist
+++ b/Sources/iOS/App/Settings.bundle/com.mono0926.LicensePlist.plist
@@ -194,14 +194,6 @@
Type
PSChildPaneSpecifier
-
- File
- com.mono0926.LicensePlist/Starscream
- Title
- Starscream (3.1.1)
- Type
- PSChildPaneSpecifier
-
File
com.mono0926.LicensePlist/SVProgressHUD
diff --git a/Sources/iOS/App/Settings.bundle/com.mono0926.LicensePlist/Starscream.plist b/Sources/iOS/App/Settings.bundle/com.mono0926.LicensePlist/Starscream.plist
deleted file mode 100644
index 251b98d1e..000000000
--- a/Sources/iOS/App/Settings.bundle/com.mono0926.LicensePlist/Starscream.plist
+++ /dev/null
@@ -1,190 +0,0 @@
-
-
-
-
- PreferenceSpecifiers
-
-
- FooterText
- Apache License
- Version 2.0, January 2004
- http://www.apache.org/licenses/
-
- Copyright (c) 2014-2016 Dalton Cherry.
-
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
- 1. Definitions.
-
- "License" shall mean the terms and conditions for use, reproduction,
- and distribution as defined by Sections 1 through 9 of this document.
-
- "Licensor" shall mean the copyright owner or entity authorized by
- the copyright owner that is granting the License.
-
- "Legal Entity" shall mean the union of the acting entity and all
- other entities that control, are controlled by, or are under common
- control with that entity. For the purposes of this definition,
- "control" means (i) the power, direct or indirect, to cause the
- direction or management of such entity, whether by contract or
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
- outstanding shares, or (iii) beneficial ownership of such entity.
-
- "You" (or "Your") shall mean an individual or Legal Entity
- exercising permissions granted by this License.
-
- "Source" form shall mean the preferred form for making modifications,
- including but not limited to software source code, documentation
- source, and configuration files.
-
- "Object" form shall mean any form resulting from mechanical
- transformation or translation of a Source form, including but
- not limited to compiled object code, generated documentation,
- and conversions to other media types.
-
- "Work" shall mean the work of authorship, whether in Source or
- Object form, made available under the License, as indicated by a
- copyright notice that is included in or attached to the work
- (an example is provided in the Appendix below).
-
- "Derivative Works" shall mean any work, whether in Source or Object
- form, that is based on (or derived from) the Work and for which the
- editorial revisions, annotations, elaborations, or other modifications
- represent, as a whole, an original work of authorship. For the purposes
- of this License, Derivative Works shall not include works that remain
- separable from, or merely link (or bind by name) to the interfaces of,
- the Work and Derivative Works thereof.
-
- "Contribution" shall mean any work of authorship, including
- the original version of the Work and any modifications or additions
- to that Work or Derivative Works thereof, that is intentionally
- submitted to Licensor for inclusion in the Work by the copyright owner
- or by an individual or Legal Entity authorized to submit on behalf of
- the copyright owner. For the purposes of this definition, "submitted"
- means any form of electronic, verbal, or written communication sent
- to the Licensor or its representatives, including but not limited to
- communication on electronic mailing lists, source code control systems,
- and issue tracking systems that are managed by, or on behalf of, the
- Licensor for the purpose of discussing and improving the Work, but
- excluding communication that is conspicuously marked or otherwise
- designated in writing by the copyright owner as "Not a Contribution."
-
- "Contributor" shall mean Licensor and any individual or Legal Entity
- on behalf of whom a Contribution has been received by Licensor and
- subsequently incorporated within the Work.
-
- 2. Grant of Copyright License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- copyright license to reproduce, prepare Derivative Works of,
- publicly display, publicly perform, sublicense, and distribute the
- Work and such Derivative Works in Source or Object form.
-
- 3. Grant of Patent License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- (except as stated in this section) patent license to make, have made,
- use, offer to sell, sell, import, and otherwise transfer the Work,
- where such license applies only to those patent claims licensable
- by such Contributor that are necessarily infringed by their
- Contribution(s) alone or by combination of their Contribution(s)
- with the Work to which such Contribution(s) was submitted. If You
- institute patent litigation against any entity (including a
- cross-claim or counterclaim in a lawsuit) alleging that the Work
- or a Contribution incorporated within the Work constitutes direct
- or contributory patent infringement, then any patent licenses
- granted to You under this License for that Work shall terminate
- as of the date such litigation is filed.
-
- 4. Redistribution. You may reproduce and distribute copies of the
- Work or Derivative Works thereof in any medium, with or without
- modifications, and in Source or Object form, provided that You
- meet the following conditions:
-
- (a) You must give any other recipients of the Work or
- Derivative Works a copy of this License; and
-
- (b) You must cause any modified files to carry prominent notices
- stating that You changed the files; and
-
- (c) You must retain, in the Source form of any Derivative Works
- that You distribute, all copyright, patent, trademark, and
- attribution notices from the Source form of the Work,
- excluding those notices that do not pertain to any part of
- the Derivative Works; and
-
- (d) If the Work includes a "NOTICE" text file as part of its
- distribution, then any Derivative Works that You distribute must
- include a readable copy of the attribution notices contained
- within such NOTICE file, excluding those notices that do not
- pertain to any part of the Derivative Works, in at least one
- of the following places: within a NOTICE text file distributed
- as part of the Derivative Works; within the Source form or
- documentation, if provided along with the Derivative Works; or,
- within a display generated by the Derivative Works, if and
- wherever such third-party notices normally appear. The contents
- of the NOTICE file are for informational purposes only and
- do not modify the License. You may add Your own attribution
- notices within Derivative Works that You distribute, alongside
- or as an addendum to the NOTICE text from the Work, provided
- that such additional attribution notices cannot be construed
- as modifying the License.
-
- You may add Your own copyright statement to Your modifications and
- may provide additional or different license terms and conditions
- for use, reproduction, or distribution of Your modifications, or
- for any such Derivative Works as a whole, provided Your use,
- reproduction, and distribution of the Work otherwise complies with
- the conditions stated in this License.
-
- 5. Submission of Contributions. Unless You explicitly state otherwise,
- any Contribution intentionally submitted for inclusion in the Work
- by You to the Licensor shall be under the terms and conditions of
- this License, without any additional terms or conditions.
- Notwithstanding the above, nothing herein shall supersede or modify
- the terms of any separate license agreement you may have executed
- with Licensor regarding such Contributions.
-
- 6. Trademarks. This License does not grant permission to use the trade
- names, trademarks, service marks, or product names of the Licensor,
- except as required for reasonable and customary use in describing the
- origin of the Work and reproducing the content of the NOTICE file.
-
- 7. Disclaimer of Warranty. Unless required by applicable law or
- agreed to in writing, Licensor provides the Work (and each
- Contributor provides its Contributions) on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- implied, including, without limitation, any warranties or conditions
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
- PARTICULAR PURPOSE. You are solely responsible for determining the
- appropriateness of using or redistributing the Work and assume any
- risks associated with Your exercise of permissions under this License.
-
- 8. Limitation of Liability. In no event and under no legal theory,
- whether in tort (including negligence), contract, or otherwise,
- unless required by applicable law (such as deliberate and grossly
- negligent acts) or agreed to in writing, shall any Contributor be
- liable to You for damages, including any direct, indirect, special,
- incidental, or consequential damages of any character arising as a
- result of this License or out of the use or inability to use the
- Work (including but not limited to damages for loss of goodwill,
- work stoppage, computer failure or malfunction, or any and all
- other commercial damages or losses), even if such Contributor
- has been advised of the possibility of such damages.
-
- 9. Accepting Warranty or Additional Liability. While redistributing
- the Work or Derivative Works thereof, You may choose to offer,
- and charge a fee for, acceptance of support, warranty, indemnity,
- or other liability obligations and/or rights consistent with this
- License. However, in accepting such obligations, You may act only
- on Your own behalf and on Your sole responsibility, not on behalf
- of any other Contributor, and only if You agree to indemnify,
- defend, and hold each Contributor harmless for any liability
- incurred by, or claims asserted against, such Contributor by reason
- of your accepting any such warranty or additional liability.
- Type
- PSGroupSpecifier
-
-
-
-
diff --git a/Sources/iOS/App/Timelines/TimeLineTableViewController.swift b/Sources/iOS/App/Timelines/TimeLineTableViewController.swift
index ef5ac9b43..52dc0b57c 100644
--- a/Sources/iOS/App/Timelines/TimeLineTableViewController.swift
+++ b/Sources/iOS/App/Timelines/TimeLineTableViewController.swift
@@ -355,47 +355,20 @@ class TimeLineTableViewController: UIViewController, Instantiatable {
guard let webSocketEndpoint = self.websocketEndpoint() else {
return
}
+ if let socket = socket {
+ socket.connect()
+ return
+ }
environment.getWebSocket(endpoint: webSocketEndpoint).then { socket in
- socket.event.connect.on {
- self.streamingNavigationItem?.tintColor = nil
- }
- socket.event.disconnect.on { _ in
- self.streamingNavigationItem?.tintColor = UIColor(red: 1, green: 0.3, blue: 0.15, alpha: 1)
- }
- socket.event.message.on { text in
- var object = JSON(parseJSON: text)
- if object["event"].string == "update" {
- object["payload"] = JSON(parseJSON: object["payload"].string ?? "{}")
- self.addNewPosts(posts: [try! MastodonPost.decode(json: object["payload"])])
- } else if object["event"].string == "delete" {
- let deletedTootID = object["payload"].stringValue
- let snapshot = self.diffableDataSource.snapshot()
- var deletePosts: [TableBody] = []
-
- for body in snapshot.itemIdentifiers(inSection: .posts) {
- if case .post(let id, _) = body {
- if id.string == deletedTootID {
- deletePosts.append(body)
- } else if self.environment.memoryStore.post.container[id]?.repost?.value.id.string == deletedTootID {
- deletePosts.append(body)
- }
- }
- }
-
- if deletePosts.count > 0 {
- self.diffableDataSource.apply(snapshot, animatingDifferences: true)
- }
- } else {
- print(object)
- }
- }
+ socket.delegate = self
+ socket.connect()
self.socket = socket
}
}
@objc func streamingStatusTapped() {
print("called")
- let nowStreamConnected = (socket?.webSocket.isConnected ?? false)
+ let nowStreamConnected = (socket?.isConnected ?? false)
let alertVC = UIAlertController(
title: R.string.localizable.streaming(),
message: R.string.localizable.streamingStatus(
@@ -408,6 +381,7 @@ class TimeLineTableViewController: UIViewController, Instantiatable {
alertVC.popoverPresentationController?.barButtonItem = self.streamingNavigationItem
if nowStreamConnected {
alertVC.addAction(UIAlertAction(title: R.string.localizable.disconnect(), style: .default, handler: { (action) in
+ self.socket?.reconnect = false
self.socket?.disconnect()
}))
} else {
@@ -416,7 +390,8 @@ class TimeLineTableViewController: UIViewController, Instantiatable {
}))
}
alertVC.addAction(UIAlertAction(title: R.string.localizable.refetch(), style: .default, handler: { (action) in
- let isStreamingConnectingNow = self.socket?.webSocket.isConnected ?? false
+ let isStreamingConnectingNow = self.socket?.isConnected ?? false
+ self.socket?.reconnect = false
if isStreamingConnectingNow {
self.socket?.disconnect()
}
@@ -526,3 +501,41 @@ extension TimeLineTableViewController: UITableViewDelegate {
MastodonMemoryStoreContainer[self.environment].post.change(obj: from)
}
}
+
+extension TimeLineTableViewController: WebSocketWrapperDelegate {
+ func webSocket(_ wrapper: WebSocketWrapper, connected protocol: String?) {
+ self.streamingNavigationItem?.tintColor = nil
+ }
+
+ func webSocket(_ wrapper: WebSocketWrapper, disconnected error: Error?) {
+ self.streamingNavigationItem?.tintColor = UIColor(red: 1, green: 0.3, blue: 0.15, alpha: 1)
+ }
+
+ func webSocket(_ wrapper: WebSocketWrapper, received text: String) {
+ var object = JSON(parseJSON: text)
+ if object["event"].string == "update" {
+ object["payload"] = JSON(parseJSON: object["payload"].string ?? "{}")
+ self.addNewPosts(posts: [try! MastodonPost.decode(json: object["payload"])])
+ } else if object["event"].string == "delete" {
+ let deletedTootID = object["payload"].stringValue
+ let snapshot = self.diffableDataSource.snapshot()
+ var deletePosts: [TableBody] = []
+
+ for body in snapshot.itemIdentifiers(inSection: .posts) {
+ if case .post(let id, _) = body {
+ if id.string == deletedTootID {
+ deletePosts.append(body)
+ } else if self.environment.memoryStore.post.container[id]?.repost?.value.id.string == deletedTootID {
+ deletePosts.append(body)
+ }
+ }
+ }
+
+ if deletePosts.count > 0 {
+ self.diffableDataSource.apply(snapshot, animatingDifferences: true)
+ }
+ } else {
+ print(object)
+ }
+ }
+}
diff --git a/Sources/iOS/App/WebSocketWrapper.swift b/Sources/iOS/App/WebSocketWrapper.swift
index f734f8a65..28993e5c2 100644
--- a/Sources/iOS/App/WebSocketWrapper.swift
+++ b/Sources/iOS/App/WebSocketWrapper.swift
@@ -22,61 +22,109 @@
//
import Foundation
-import Starscream
import Hydra
import iMastiOSCore
var webSockets: [WebSocketWrapper] = []
-class WebSocketWrapper {
- let webSocket: WebSocket
+class WebSocketWrapper: NSObject {
+ private let request: URLRequest
+ private lazy var urlSession = URLSession(configuration: .ephemeral, delegate: self, delegateQueue: nil)
+ private var task: URLSessionWebSocketTask!
var reconnect: Bool = true
var reconnectWait: Int8 = 0
+ var isConnected = false
+ var timer: Timer?
+ weak var delegate: WebSocketWrapperDelegate?
- let event = WebSocketWrapperEvents()
- class WebSocketWrapperEvents {
- let connect = Event()
- let disconnect = Event()
- let message = Event()
+ init(request: URLRequest) {
+ self.request = request
+ super.init()
}
- init(webSocket: WebSocket) {
- self.webSocket = webSocket
- self.event.connect.on {
- self.reconnectWait = 0
- }
- self.event.disconnect.onBackground {_ in
- if !self.reconnect {
- return
- }
- sleep(UInt32(self.reconnectWait))
- if self.reconnectWait < 10 {
- self.reconnectWait += 1
+ func receiveLoop() {
+ task.receive { result in
+ switch result {
+ case .success(let data):
+ switch data {
+ case .string(let str):
+ DispatchQueue.main.async {
+ self.delegate?.webSocket?(self, received: str)
+ }
+ default:
+ print("unknown \(data)")
+ }
+ self.receiveLoop()
+ case .failure(let error):
+ self.disconnect(error: error)
}
- self.webSocket.connect()
}
- self.webSocket.onConnect = {
- self.event.connect.emit(Void())
+ }
+
+ func connect() {
+ reconnect = true
+ task = urlSession.webSocketTask(with: request)
+ receiveLoop()
+ task.resume()
+ }
+
+ func disconnect(error: Error? = nil) {
+ print("WebSocket::Disconenct", error)
+ guard self.isConnected == true else {
+ print("いやisConnected==falseじゃねえか")
+ return
+ }
+ self.isConnected = false
+ print("")
+ task.cancel(with: .goingAway, reason: nil)
+ timer?.invalidate()
+ if reconnect {
+ DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(Int(reconnectWait))) {
+ if self.reconnectWait < 10 {
+ self.reconnectWait += 1
+ }
+ self.connect()
+ }
}
- self.webSocket.onDisconnect = { error in
- self.event.disconnect.emit(error)
+ DispatchQueue.main.async {
+ self.delegate?.webSocket?(self, disconnected: error)
}
- self.webSocket.onText = { content in
- self.event.message.emit(content)
+ }
+
+ @objc func sendPing() {
+ print(task.closeCode.rawValue, task.closeReason, task.state.rawValue, task.error)
+ }
+}
+
+extension WebSocketWrapper: URLSessionWebSocketDelegate {
+ func urlSession(_ session: URLSession, webSocketTask: URLSessionWebSocketTask, didOpenWithProtocol protocol: String?) {
+ print("WebSocket::Connected")
+ self.reconnectWait = 0
+ self.isConnected = true
+ self.timer = .scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.sendPing), userInfo: nil, repeats: true)
+ self.timer?.fire()
+ DispatchQueue.main.async {
+ self.delegate?.webSocket?(self, connected: `protocol`)
}
}
- func disconnect() {
- self.reconnect = false
- self.webSocket.disconnect()
+ func urlSession(_ session: URLSession, webSocketTask: URLSessionWebSocketTask, didCloseWith closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?) {
+ print("urlSession(_:webSocketTask:didCloseWith:reason:)")
+ disconnect()
}
- func connect() {
- self.reconnect = true
- self.webSocket.connect()
+ func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
+ print("urlSession(_:task:didCompleteWithError:)", error)
+ print(error)
}
}
+@objc protocol WebSocketWrapperDelegate {
+ @objc optional func webSocket(_ wrapper: WebSocketWrapper, connected protocol: String?)
+ @objc optional func webSocket(_ wrapper: WebSocketWrapper, disconnected error: Error?)
+ @objc optional func webSocket(_ wrapper: WebSocketWrapper, received text: String)
+}
+
extension MastodonUserToken {
func getWebSocket(endpoint: String) -> Promise {
return self.app.instance.getInfo().then { info in
@@ -92,15 +140,10 @@ extension MastodonUserToken {
}
var urlRequest = URLRequest(url: URL(string: streamingUrlString)!)
urlRequest.addValue(UserAgentString, forHTTPHeaderField: "User-Agent")
- let webSocket = WebSocket(request: urlRequest, protocols: protocols)
- let wrap = WebSocketWrapper(webSocket: webSocket)
- _ = wrap.event.connect.on {
- print("WebSocket::Connect", endpoint)
- }
- _ = wrap.event.disconnect.on { error in
- print("WebSocket::Disconnect", endpoint, error?.localizedDescription ?? "no desc")
+ if let protocols = protocols {
+ urlRequest.addValue(protocols.joined(separator: ","), forHTTPHeaderField: "Sec-WebSocket-Protocol")
}
- wrap.connect()
+ let wrap = WebSocketWrapper(request: urlRequest)
webSockets.append(wrap)
return Promise(resolved: wrap)
}
diff --git a/Sources/iOS/Core_NonLib/EventListener.swift b/Sources/iOS/Core_NonLib/EventListener.swift
index 16723e716..90d77e467 100644
--- a/Sources/iOS/Core_NonLib/EventListener.swift
+++ b/Sources/iOS/Core_NonLib/EventListener.swift
@@ -52,9 +52,11 @@ class Event {
}
}
func emit(_ content: T) {
- listeners.forEach { (arg) in
- let (_, listener) = arg
- listener(content)
+ DispatchQueue.main.async { [weak self] in
+ self?.listeners.forEach { (arg) in
+ let (_, listener) = arg
+ listener(content)
+ }
}
}
func unsubscribe(id: String) {