Branchwell

Inkspring / app · inkspring.ai / native-mac / Sources / Inkspring / SubstackSession.swift

1import Foundation
2import WebKit
3
4@MainActor
5final class SubstackSession {
6 lazy var storage = DailyBackup.usesTestWorkspace
7 ? WKWebsiteDataStore.nonPersistent()
8 : WKWebsiteDataStore(forIdentifier: UUID(uuidString: "CCB7C9C0-5EBA-4287-8C24-F910B2A468F3")!)
9 private var nextRequest = ContinuousClock.now
10 private let network: URLSession = {
11 let configuration = URLSessionConfiguration.ephemeral
12 configuration.httpShouldSetCookies = false
13 configuration.httpCookieStorage = nil
14 configuration.urlCache = nil
15 configuration.timeoutIntervalForRequest = 30
16 configuration.timeoutIntervalForResource = 60
17 return URLSession(configuration: configuration, delegate: NoHTTPRedirects(), delegateQueue: nil)
18 }()
19
20 static func host(_ url: URL) -> String? {
21 guard url.scheme == "https", url.user == nil, url.password == nil, url.port == nil,
22 let host = url.host(), host == "substack.com" ||
23 host.range(of: #"^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.substack\.com$"#, options: .regularExpression) != nil else { return nil }
24 return host
25 }
26
27 static func loginAddress(_ url: URL) -> Bool {
28 host(url) != nil || (url.scheme == "https" && url.user == nil && url.password == nil && url.port == nil &&
29 ["accounts.google.com", "appleid.apple.com"].contains(url.host() ?? ""))
30 }
31
32 func clear() async {
33 await storage.removeData(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes(), modifiedSince: .distantPast)
34 }
35
36 func request(_ method: String, _ url: URL, _ payload: [String: Any]?) async throws -> [String: Any] {
37 guard let host = Self.host(url) else { throw WorkspaceError("This request requires a Substack address.") }
38 try await ContinuousClock().sleep(until: nextRequest)
39 nextRequest = ContinuousClock.now + .seconds(1)
40 let cookies = await storage.httpCookieStore.allCookies().filter { cookie in
41 guard cookie.expiresDate.map({ $0 > Date.now }) ?? true else { return false }
42 let domain = cookie.domain.lowercased()
43 let domainMatches = host == domain || (domain.hasPrefix(".") && ("." + host).hasSuffix(domain))
44 let path = cookie.path
45 let pathMatches = url.path == path || url.path.hasPrefix(path.hasSuffix("/") ? path : path + "/")
46 return domainMatches && pathMatches
47 }
48 guard cookies.contains(where: { ["substack.sid", "connect.sid"].contains($0.name) }) else {
49 throw WorkspaceError("Sign in to Substack in Connections.")
50 }
51 var request = URLRequest(url: url)
52 request.httpMethod = method
53 request.setValue("application/json", forHTTPHeaderField: "Accept")
54 request.setValue("https://\(host)", forHTTPHeaderField: "Origin")
55 request.setValue("https://\(host)/", forHTTPHeaderField: "Referer")
56 for (field, value) in HTTPCookie.requestHeaderFields(with: cookies) {
57 request.setValue(value, forHTTPHeaderField: field)
58 }
59 if let payload {
60 request.httpBody = try JSONSerialization.data(withJSONObject: payload)
61 request.setValue("application/json", forHTTPHeaderField: "Content-Type")
62 }
63 let (bytes, response): (URLSession.AsyncBytes, URLResponse)
64 do { (bytes, response) = try await network.bytes(for: request) }
65 catch { throw SubstackRequestError("Substack did not confirm the request. Check its editor before trying again.", uncertain: method != "GET") }
66 let status = (response as? HTTPURLResponse)?.statusCode ?? 0
67 switch status {
68 case 200..<300: break
69 case 401, 403: throw WorkspaceError("Sign in to Substack again and check your publication permissions.")
70 case 429: throw WorkspaceError("Substack is limiting requests. Wait a few minutes before trying again.")
71 default: throw SubstackRequestError("Substack returned HTTP \(status).", uncertain: method != "GET" && (status < 400 || status >= 500))
72 }
73 do {
74 let limit = 5_000_000
75 guard response.expectedContentLength <= limit else { throw WorkspaceError("Substack returned too much data.") }
76 var data = Data()
77 for try await byte in bytes {
78 guard data.count < limit else { throw WorkspaceError("Substack returned too much data.") }
79 data.append(byte)
80 }
81 if data.isEmpty { return [:] }
82 guard let object = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {
83 throw WorkspaceError("Substack returned an unreadable response.")
84 }
85 return object
86 } catch {
87 throw SubstackRequestError("Substack returned an unreadable response. Check its editor before trying again.", uncertain: method != "GET")
88 }
89 }
90}
91
92struct SubstackRequestError: LocalizedError {
93 let errorDescription: String?
94 let uncertain: Bool
95
96 init(_ message: String, uncertain: Bool) {
97 errorDescription = message
98 self.uncertain = uncertain
99 }
100}