-
Notifications
You must be signed in to change notification settings - Fork 152
Expand file tree
/
Copy pathclient.swift
More file actions
executable file
Β·219 lines (191 loc) Β· 6.97 KB
/
Copy pathclient.swift
File metadata and controls
executable file
Β·219 lines (191 loc) Β· 6.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
#!/usr/bin/env swift
import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
struct HTTPResult {
let statusCode: Int
let body: String
}
enum ClientError: Error, CustomStringConvertible {
case invalidBaseURL(String)
case invalidURL(String)
case requestFailed(Error)
case missingHTTPResponse
var description: String {
switch self {
case .invalidBaseURL(let value):
return "Invalid AIOGRAPI_REST_BASE_URL: \(value)"
case .invalidURL(let value):
return "Invalid URL: \(value)"
case .requestFailed(let error):
return "Request failed: \(error)"
case .missingHTTPResponse:
return "Missing HTTP response"
}
}
}
final class APIClient {
private let baseURL: URL
var sessionID: String?
init(baseURL: String, sessionID: String?) throws {
guard let url = URL(string: baseURL) else {
throw ClientError.invalidBaseURL(baseURL)
}
self.baseURL = url
self.sessionID = sessionID
}
func get(_ path: String, queryItems: [URLQueryItem] = []) throws -> HTTPResult {
try request("GET", path: path, queryItems: queryItems)
}
func postForm(_ path: String, fields: [String: String]) throws -> HTTPResult {
try request(
"POST",
path: path,
body: formBody(fields),
contentType: "application/x-www-form-urlencoded"
)
}
func login(username: String, password: String, verificationCode: String?) throws -> HTTPResult {
var fields = [
"username": username,
"password": password,
]
if let verificationCode {
fields["verification_code"] = verificationCode
}
return try postForm("/auth/login", fields: fields)
}
func importInstagramSessionID(_ instagramSessionID: String) throws -> HTTPResult {
try postForm("/auth/login/by/sessionid", fields: ["sessionid": instagramSessionID])
}
private func request(
_ method: String,
path: String,
queryItems: [URLQueryItem] = [],
body: Data? = nil,
contentType: String? = nil
) throws -> HTTPResult {
let cleanPath = path.trimmingCharacters(in: CharacterSet(charactersIn: "/"))
var url = baseURL.appendingPathComponent(cleanPath)
if !queryItems.isEmpty {
guard var components = URLComponents(url: url, resolvingAgainstBaseURL: false) else {
throw ClientError.invalidURL(url.absoluteString)
}
components.queryItems = queryItems
guard let composedURL = components.url else {
throw ClientError.invalidURL(url.absoluteString)
}
url = composedURL
}
var request = URLRequest(url: url)
request.httpMethod = method
request.setValue("application/json", forHTTPHeaderField: "Accept")
if let sessionID {
request.setValue(sessionID, forHTTPHeaderField: "X-Session-ID")
}
if let contentType {
request.setValue(contentType, forHTTPHeaderField: "Content-Type")
}
request.httpBody = body
let semaphore = DispatchSemaphore(value: 0)
var responseData: Data?
var response: URLResponse?
var responseError: Error?
URLSession.shared.dataTask(with: request) { data, urlResponse, error in
responseData = data
response = urlResponse
responseError = error
semaphore.signal()
}.resume()
semaphore.wait()
if let responseError {
throw ClientError.requestFailed(responseError)
}
guard let httpResponse = response as? HTTPURLResponse else {
throw ClientError.missingHTTPResponse
}
return HTTPResult(
statusCode: httpResponse.statusCode,
body: responseData.flatMap { String(data: $0, encoding: .utf8) } ?? ""
)
}
}
func formBody(_ fields: [String: String]) -> Data {
var components = URLComponents()
components.queryItems = fields.map { URLQueryItem(name: $0.key, value: $0.value) }
return Data((components.percentEncodedQuery ?? "").utf8)
}
func env(_ name: String) -> String? {
let value = ProcessInfo.processInfo.environment[name]?.trimmingCharacters(in: .whitespacesAndNewlines)
return value?.isEmpty == false ? value : nil
}
func prettyBody(_ body: String) -> String {
guard let data = body.data(using: .utf8),
let json = try? JSONSerialization.jsonObject(with: data),
JSONSerialization.isValidJSONObject(json),
let pretty = try? JSONSerialization.data(withJSONObject: json, options: [.prettyPrinted, .sortedKeys]),
let rendered = String(data: pretty, encoding: .utf8) else {
return body
}
return rendered
}
func printResult(_ title: String, _ result: HTTPResult) {
print("\n\(title) [HTTP \(result.statusCode)]")
print(prettyBody(result.body))
}
func sessionID(from body: String) -> String? {
guard let data = body.data(using: .utf8),
let value = try? JSONDecoder().decode(String.self, from: data),
!value.isEmpty,
value != "false" else {
return nil
}
return value
}
do {
let client = try APIClient(
baseURL: env("AIOGRAPI_REST_BASE_URL") ?? "http://localhost:8000",
sessionID: env("AIOGRAPI_REST_SESSIONID")
)
printResult("Health", try client.get("/health"))
printResult("Dependencies", try client.get("/deps"))
if client.sessionID == nil,
let instagramSessionID = env("AIOGRAPI_REST_INSTAGRAM_SESSIONID") {
let login = try client.importInstagramSessionID(instagramSessionID)
printResult("Import Session", login)
client.sessionID = sessionID(from: login.body)
if client.sessionID != nil {
print("\nImported session stored for this process.")
}
}
if client.sessionID == nil,
let username = env("AIOGRAPI_REST_USERNAME"),
let password = env("AIOGRAPI_REST_PASSWORD") {
let login = try client.login(
username: username,
password: password,
verificationCode: env("AIOGRAPI_REST_VERIFICATION_CODE")
)
printResult("Login", login)
client.sessionID = sessionID(from: login.body)
if client.sessionID != nil {
print("\nLogin stored the returned session for this process.")
}
}
if client.sessionID != nil {
let userID = env("AIOGRAPI_REST_USER_ID") ?? "25025320"
printResult(
"User About",
try client.get("/user/about", queryItems: [URLQueryItem(name: "user_id", value: userID)])
)
} else {
print(
"\nSet AIOGRAPI_REST_SESSIONID, AIOGRAPI_REST_INSTAGRAM_SESSIONID, " +
"or AIOGRAPI_REST_USERNAME/AIOGRAPI_REST_PASSWORD to call /user/about."
)
}
} catch {
fputs("\(error)\n", stderr)
exit(1)
}