Skip to content

Commit 9ec6ddc

Browse files
committed
refactor: 脱 SwiftyJSON
1 parent caf6d3f commit 9ec6ddc

File tree

14 files changed

+82
-181
lines changed

14 files changed

+82
-181
lines changed

Podfile

-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@ abstract_target 'iMastShared' do
1111
def core_pods
1212
pod 'GRDB.swift', '~> 4.6.2', :linkage => :static
1313
end
14-
pod 'SwiftyJSON', '5.0.0'
1514
pod 'HydraAsync', '~> 2.0.6'
1615
pod 'SDWebImage', '~> 5.12.6'
1716
pod 'Fuzi', '~> 3.1.3'

Podfile.lock

+1-5
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@ PODS:
1616
- Starscream (3.1.1)
1717
- SwiftGen (6.5.1)
1818
- SwiftLint (0.52.4)
19-
- SwiftyJSON (5.0.0)
2019

2120
DEPENDENCIES:
2221
- Alamofire (~> 4.9.1)
@@ -32,7 +31,6 @@ DEPENDENCIES:
3231
- Starscream (~> 3.1.1)
3332
- SwiftGen (= 6.5.1)
3433
- SwiftLint (= 0.52.4)
35-
- SwiftyJSON (= 5.0.0)
3634

3735
SPEC REPOS:
3836
trunk:
@@ -48,7 +46,6 @@ SPEC REPOS:
4846
- Starscream
4947
- SwiftGen
5048
- SwiftLint
51-
- SwiftyJSON
5249

5350
EXTERNAL SOURCES:
5451
Mew:
@@ -74,8 +71,7 @@ SPEC CHECKSUMS:
7471
Starscream: 4bb2f9942274833f7b4d296a55504dcfc7edb7b0
7572
SwiftGen: a6d22010845f08fe18fbdf3a07a8e380fd22e0ea
7673
SwiftLint: 1cc5cd61ba9bacb2194e340aeb47a2a37fda00b3
77-
SwiftyJSON: 36413e04c44ee145039d332b4f4e2d3e8d6c4db7
7874

79-
PODFILE CHECKSUM: eec6d544bb8107e88e88e4075992f435b33bed36
75+
PODFILE CHECKSUM: 625b70b19f2dca2402959b351e5fff797553261f
8076

8177
COCOAPODS: 1.13.0

Sources/Core/Mastodon/Endpoint/MastodonEndpoint.swift

+22
Original file line numberDiff line numberDiff line change
@@ -56,4 +56,26 @@ extension MastodonEndpoint {
5656
case postIds = "status_ids"
5757
}
5858
}
59+
60+
public struct VerifyCredentials: MastodonEndpointProtocol {
61+
public struct Response: MastodonEndpointResponse, Decodable {
62+
let displayName: String
63+
let screenName: String
64+
let avatar: String
65+
public let source: Source?
66+
67+
public struct Source: Decodable {
68+
public let privacy: String
69+
}
70+
71+
enum CodingKeys: String, CodingKey {
72+
case displayName = "display_name"
73+
case screenName = "username"
74+
case avatar = "avatar_static"
75+
case source
76+
}
77+
}
78+
public let endpoint = "/api/v1/accounts/verify_credentials"
79+
public let method = "GET"
80+
}
5981
}

Sources/Core/Mastodon/Model/MastodonApp.swift

+3-4
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,6 @@
2222
// limitations under the License.
2323

2424
import Foundation
25-
import SwiftyJSON
2625
import Alamofire
2726
import GRDB
2827

@@ -44,10 +43,10 @@ public class MastodonApp: Hashable {
4443
public var instance: MastodonInstance
4544
var id: String
4645

47-
init(instance: MastodonInstance, info: JSON, name: String, redirectUri: String) {
46+
init(instance: MastodonInstance, info: MastodonInstance.CreateAppResponse, name: String, redirectUri: String) {
4847
self.instance = instance
49-
clientId = info["client_id"].stringValue
50-
clientSecret = info["client_secret"].stringValue
48+
clientId = info.clientId
49+
clientSecret = info.clientSecret
5150
self.name = name
5251
self.redirectUri = redirectUri
5352
self.id = genRandomString()

Sources/Core/Mastodon/Model/MastodonInstance.swift

+32-13
Original file line numberDiff line numberDiff line change
@@ -22,11 +22,8 @@
2222
// limitations under the License.
2323

2424
import Foundation
25-
import SwiftyJSON
26-
import Hydra
27-
//import Alamofire
2825

29-
var mastodonInstanceInfoCache: [String: JSON] = [:]
26+
var mastodonInstanceInfoCache: [String: MastodonInstance.Info] = [:]
3027

3128
#if os(macOS)
3229
public let defaultAppName = "iMast (macOS)"
@@ -37,10 +34,35 @@ private let website = "https://cinderella-project.github.io/iMast/"
3734
#endif
3835

3936
public class MastodonInstance {
37+
public struct Info: Codable {
38+
public let version: String
39+
public let urls: Urls
40+
41+
public struct Urls: Codable {
42+
public let streamingApi: String
43+
44+
enum CodingKeys: String, CodingKey {
45+
case streamingApi = "streaming_api"
46+
}
47+
}
48+
49+
enum CodingKeys: String, CodingKey {
50+
case version
51+
case urls
52+
}
53+
}
54+
55+
struct CreateAppResponse: Codable {
56+
let clientId: String
57+
let clientSecret: String
58+
59+
enum CodingKeys: String, CodingKey {
60+
case clientId = "client_id"
61+
case clientSecret = "client_secret"
62+
}
63+
}
64+
4065
public var hostName: String
41-
public var name: String?
42-
var description: String?
43-
var email: String?
4466
public var url: URL {
4567
return URL(string: "https://\(self.hostName)")!
4668
}
@@ -49,18 +71,15 @@ public class MastodonInstance {
4971
self.hostName = hostName.replacing(/.+@/, with: "").lowercased()
5072
}
5173

52-
public func getInfo() async throws -> JSON {
74+
public func getInfo() async throws -> Info {
5375
if let cache = mastodonInstanceInfoCache[self.hostName] {
5476
return cache
5577
}
5678
var request = try URLRequest(url: URL(string: "https://\(hostName)/api/v1/instance")!, method: .get)
5779
request.setValue(UserAgentString, forHTTPHeaderField: "User-Agent")
5880
let data = try await MastodonAPI.handleHTTPError(URLSession.shared.data(for: request))
59-
let json = try JSON(data: data)
81+
let json = try JSONDecoder.forMastodonAPI.decode(Info.self, from: data)
6082

61-
self.name = json["name"].string
62-
self.description = json["description"].string
63-
self.email = json["email"].string
6483
mastodonInstanceInfoCache[self.hostName] = json
6584
return json
6685
}
@@ -77,7 +96,7 @@ public class MastodonInstance {
7796
request.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type")
7897
request.httpBody = try JSONEncoder().encode(params)
7998
let data = try await MastodonAPI.handleHTTPError(URLSession.shared.data(for: request))
80-
let json = try JSON(data: data)
99+
let json = try JSONDecoder.forMastodonAPI.decode(CreateAppResponse.self, from: data)
81100

82101
return MastodonApp(instance: self, info: json, name: name, redirectUri: redirect_uri)
83102
}

Sources/Core/Mastodon/Model/MastodonUserToken.swift

+8-43
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,6 @@
2222
// limitations under the License.
2323

2424
import Foundation
25-
import SwiftyJSON
2625
import Alamofire
2726
import Hydra
2827
import GRDB
@@ -59,7 +58,7 @@ public class MastodonUserToken: Equatable, @unchecked Sendable {
5958
}
6059

6160
public func getIntVersion() async throws -> MastodonVersionInt {
62-
return MastodonVersionInt(try await self.app.instance.getInfo()["version"].stringValue)
61+
return MastodonVersionInt(try await self.app.instance.getInfo().version)
6362
}
6463

6564
static public func initFromId(id: String) -> MastodonUserToken? {
@@ -201,25 +200,20 @@ public class MastodonUserToken: Equatable, @unchecked Sendable {
201200
}
202201
}
203202

204-
static var verifyCredentialsCache: [String: JSON] = [:]
203+
static var verifyCredentialsCache: [String: MastodonEndpoint.VerifyCredentials.Response] = [:]
205204

206-
public func getUserInfo(cache: Bool = false) async throws -> JSON {
205+
public func getUserInfo(cache: Bool = false) async throws -> MastodonEndpoint.VerifyCredentials.Response {
207206
if cache, let cacheObj = MastodonUserToken.verifyCredentialsCache[self.acct] {
208207
return cacheObj
209208
}
210-
let response = try await getJSON("accounts/verify_credentials")
211-
self.name = response["display_name"].string
212-
if self.name == nil || self.name?.isEmpty == true {
213-
self.name = response["name"].string
214-
}
215-
self.screenName = response["username"].string
216-
self.avatarUrl = response["avatar"].string
209+
let response = try await MastodonEndpoint.VerifyCredentials().request(with: self)
210+
self.name = response.displayName.isEmpty ? response.screenName : response.displayName
211+
self.screenName = response.screenName
212+
self.avatarUrl = response.avatar
217213
if let avatarUrl = self.avatarUrl, !avatarUrl.isEmpty, avatarUrl.first == "/" { // ホスト名がない!!!
218214
self.avatarUrl = "https://"+self.app.instance.hostName+self.avatarUrl!
219215
}
220-
if response["error"].isEmpty {
221-
MastodonUserToken.verifyCredentialsCache[self.acct] = response
222-
}
216+
MastodonUserToken.verifyCredentialsCache[self.acct] = response
223217
return response
224218
}
225219

@@ -257,35 +251,6 @@ public class MastodonUserToken: Equatable, @unchecked Sendable {
257251
)
258252
}
259253

260-
@available(*, deprecated)
261-
func getJSON(_ endpoint: String, params: [URLQueryItem] = []) async throws -> JSON {
262-
print("GET", endpoint)
263-
264-
var urlBuilder = URLComponents(url: URL(string: endpoint, relativeTo: URL(string: "https://\(self.app.instance.hostName)/api/v1/")!)!, resolvingAgainstBaseURL: true)!
265-
urlBuilder.queryItems = params
266-
if urlBuilder.queryItems?.count == 0 {
267-
urlBuilder.queryItems = nil
268-
}
269-
let headers = getHeader()
270-
var request = URLRequest(url: try urlBuilder.asURL())
271-
print(request.url)
272-
request.httpMethod = "GET"
273-
for (name, value) in headers {
274-
request.setValue(value, forHTTPHeaderField: name)
275-
}
276-
print(request.httpMethod!, request.url!)
277-
let (data, response) = try await URLSession.shared.data(for: request)
278-
if let response = response as? HTTPURLResponse, response.statusCode >= 400 {
279-
do {
280-
let error = try JSONDecoder.forMastodonAPI.decode(MastodonErrorResponse.self, from: data)
281-
throw APIError.errorReturned(errorMessage: error.error, errorHttpCode: response.statusCode)
282-
} catch {
283-
throw APIError.unknownResponse(errorHttpCode: response.statusCode, errorString: .init(data: data, encoding: .utf8))
284-
}
285-
}
286-
return try JSON(data: data)
287-
}
288-
289254
public func upload(file: Data, mimetype: String, filename: String = "imast_upload_file") async throws -> MastodonAttachment {
290255
let request = try await withCheckedThrowingContinuation { continuation in
291256
Alamofire.upload(

Sources/Mac/App/Generated/licenses.json

-4
Original file line numberDiff line numberDiff line change
@@ -70,9 +70,5 @@
7070
{
7171
"title": "SwiftLint (0.52.4)",
7272
"text": "The MIT License (MIT)\n\nCopyright (c) 2020 Realm Inc.\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
73-
},
74-
{
75-
"title": "SwiftyJSON (5.0.0)",
76-
"text": "The MIT License (MIT)\n\nCopyright (c) 2017 Ruoyu Fu\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n"
7773
}
7874
]

Sources/iOS/App/Screens/NewPost/NewPostViewController.swift

+13-12
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@
2323

2424
import UIKit
2525
import Hydra
26-
import SwiftyJSON
2726
import MediaPlayer
2827
import Alamofire
2928
import iMastiOSCore
@@ -313,20 +312,22 @@ class NewPostViewController: UIViewController, UITextViewDelegate {
313312
var request = URLRequest(url: URL(string: "https://itunes.apple.com/lookup?id=\(storeId)&country=\(region)&media=music")!)
314313
request.timeoutInterval = 1.5
315314
request.addValue(UserAgentString, forHTTPHeaderField: "User-Agent")
316-
Alamofire.request(request).responseData { [finished] res in
315+
Task { @MainActor in
317316
var text = nowPlayingText
318317
do {
319-
switch res.result {
320-
case .success(let data):
321-
let json = try JSON(data: data)
322-
if let url = json["results"][0]["trackViewUrl"].string {
323-
text += " " + url + " "
324-
}
325-
case .failure(let error):
326-
throw error
318+
let (data, res) = try await URLSession.shared.data(for: request)
319+
struct SearchResultWrapper: Codable {
320+
let results: [SearchResult]
321+
}
322+
struct SearchResult: Codable {
323+
let trackViewUrl: URL
324+
}
325+
let result = try JSONDecoder().decode(SearchResultWrapper.self, from: data)
326+
if let url = result.results.first?.trackViewUrl {
327+
text += " " + url.absoluteString + " "
327328
}
328329
} catch {
329-
print(error)
330+
// nothing
330331
}
331332
finished(text)
332333
}
@@ -378,7 +379,7 @@ class NewPostViewController: UIViewController, UITextViewDelegate {
378379
func setVisibilityFromUserInfo() {
379380
Task { @MainActor in
380381
let res = try await self.userToken.getUserInfo(cache: true)
381-
if let myScope = MastodonPostVisibility(rawValue: res["source"]["privacy"].string ?? "public") {
382+
if let myScope = MastodonPostVisibility(rawValue: res.source?.privacy ?? "public") {
382383
self.scope = myScope
383384
}
384385
}

Sources/iOS/App/Settings.bundle/com.mono0926.LicensePlist.latest_result.txt

-40
Original file line numberDiff line numberDiff line change
@@ -416,46 +416,6 @@ name: SwiftLint, nameSpecified:
416416
body: The MIT License (MIT…
417417
version: 0.52.4
418418

419-
name: SwiftyJSON, nameSpecified:
420-
body: The MIT License (MIT…
421-
version: 5.0.0
422-
423-
name: SwiftyJSON, nameSpecified:
424-
body: The MIT License (MIT…
425-
version: 5.0.0
426-
427-
name: SwiftyJSON, nameSpecified:
428-
body: The MIT License (MIT…
429-
version: 5.0.0
430-
431-
name: SwiftyJSON, nameSpecified:
432-
body: The MIT License (MIT…
433-
version: 5.0.0
434-
435-
name: SwiftyJSON, nameSpecified:
436-
body: The MIT License (MIT…
437-
version: 5.0.0
438-
439-
name: SwiftyJSON, nameSpecified:
440-
body: The MIT License (MIT…
441-
version: 5.0.0
442-
443-
name: SwiftyJSON, nameSpecified:
444-
body: The MIT License (MIT…
445-
version: 5.0.0
446-
447-
name: SwiftyJSON, nameSpecified:
448-
body: The MIT License (MIT…
449-
version: 5.0.0
450-
451-
name: SwiftyJSON, nameSpecified:
452-
body: The MIT License (MIT…
453-
version: 5.0.0
454-
455-
name: SwiftyJSON, nameSpecified:
456-
body: The MIT License (MIT…
457-
version: 5.0.0
458-
459419
name: mikutter, nameSpecified: , owner: mikutter, version: , source: https://github.com/mikutter/mikutter
460420

461421
name: mikutter, nameSpecified: , owner: mikutter, version: , source: https://github.com/mikutter/mikutter

Sources/iOS/App/Settings.bundle/com.mono0926.LicensePlist.plist

-8
Original file line numberDiff line numberDiff line change
@@ -154,14 +154,6 @@
154154
<key>Type</key>
155155
<string>PSChildPaneSpecifier</string>
156156
</dict>
157-
<dict>
158-
<key>File</key>
159-
<string>com.mono0926.LicensePlist/SwiftyJSON</string>
160-
<key>Title</key>
161-
<string>SwiftyJSON (5.0.0)</string>
162-
<key>Type</key>
163-
<string>PSChildPaneSpecifier</string>
164-
</dict>
165157
</array>
166158
</dict>
167159
</plist>

0 commit comments

Comments
 (0)