Mulberry/App/Services/Net.swift
astar76 8e6f8a86a4 Mulberry for iOS: initial SwiftUI port of the Android app
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 19:30:49 -05:00

72 lines
3.1 KiB
Swift

import Foundation
/// Small blocking HTTP helpers for background work (Android Net.java).
enum Net {
static let ua = "Mulberry/1.0 (iOS; +https://archlinux.tail7c4f5e.ts.net/git/astar76/Mulberry)"
private static let session: URLSession = {
let c = URLSessionConfiguration.default
c.timeoutIntervalForRequest = 15
c.httpAdditionalHeaders = ["User-Agent": ua]
return URLSession(configuration: c)
}()
static func enc(_ s: String) -> String {
s.addingPercentEncoding(withAllowedCharacters: .alphanumerics.union(CharacterSet(charactersIn: "-._~"))) ?? s
}
static func query(_ params: [(String, String)]) -> String {
params.map { "\(enc($0.0))=\(enc($0.1))" }.joined(separator: "&")
}
static func data(_ url: String, headers: [String: String] = [:], method: String = "GET", body: Data? = nil,
contentType: String? = nil) throws -> Data {
guard let u = URL(string: url) else { throw URLError(.badURL) }
var req = URLRequest(url: u)
req.httpMethod = method
req.httpBody = body
if let contentType { req.setValue(contentType, forHTTPHeaderField: "Content-Type") }
for (k, v) in headers { req.setValue(v, forHTTPHeaderField: k) }
let sem = DispatchSemaphore(value: 0)
var out: Result<Data, Error> = .failure(URLError(.unknown))
session.dataTask(with: req) { d, r, e in
if let e { out = .failure(e) }
else if let h = r as? HTTPURLResponse, h.statusCode >= 400, h.statusCode != 404 {
out = .failure(URLError(.badServerResponse))
} else { out = .success(d ?? Data()) }
sem.signal()
}.resume()
sem.wait()
return try out.get()
}
static func get(_ url: String, headers: [String: String] = [:]) throws -> String {
String(data: try data(url, headers: headers), encoding: .utf8) ?? ""
}
static func json(_ url: String, headers: [String: String] = [:]) throws -> Any {
try JSONSerialization.jsonObject(with: try data(url, headers: headers))
}
static func postForm(_ url: String, _ form: [(String, String)]) throws -> Any {
let d = try data(url, method: "POST", body: Data(query(form).utf8),
contentType: "application/x-www-form-urlencoded; charset=utf-8")
return try JSONSerialization.jsonObject(with: d)
}
static func postJSON(_ url: String, _ body: Any, headers: [String: String] = [:]) throws -> Data {
try data(url, headers: headers, method: "POST", body: try JSONSerialization.data(withJSONObject: body),
contentType: "application/json")
}
}
extension Dictionary where Key == String, Value == Any {
func str(_ k: String) -> String {
if let s = self[k] as? String, s != "<null>" { return s }
if let n = self[k] as? NSNumber { return n.stringValue }
return ""
}
func num(_ k: String) -> Double { (self[k] as? NSNumber)?.doubleValue ?? Double(str(k)) ?? 0 }
func obj(_ k: String) -> [String: Any]? { self[k] as? [String: Any] }
func arr(_ k: String) -> [[String: Any]] { self[k] as? [[String: Any]] ?? [] }
}