frenzy-ios/Fervor/FervorClient.swift

150 lines
5.2 KiB
Swift
Raw Normal View History

2021-12-08 02:58:02 +00:00
//
// FervorClient.swift
// Fervor
//
// Created by Shadowfacts on 11/25/21.
//
import Foundation
public class FervorClient {
let instanceURL: URL
let session: URLSession
public var accessToken: String?
2021-12-25 19:04:45 +00:00
private let decoder: JSONDecoder = {
let d = JSONDecoder()
2022-01-09 22:13:30 +00:00
let withFractionalSeconds = ISO8601DateFormatter()
withFractionalSeconds.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
let without = ISO8601DateFormatter()
without.formatOptions = [.withInternetDateTime]
// because fucking ISO8601DateFormatter isn't a DateFormatter
d.dateDecodingStrategy = .custom({ decoder in
let s = try decoder.singleValueContainer().decode(String.self)
// try both because Elixir's DateTime.to_iso8601 omits the .0 if the date doesn't have fractional seconds
if let d = withFractionalSeconds.date(from: s) {
return d
} else if let d = without.date(from: s) {
return d
} else {
throw DateDecodingError()
}
})
2021-12-25 19:04:45 +00:00
return d
}()
2021-12-08 02:58:02 +00:00
public init(instanceURL: URL, accessToken: String?, session: URLSession = .shared) {
self.instanceURL = instanceURL
self.accessToken = accessToken
self.session = session
}
2022-01-09 22:13:30 +00:00
private func buildURL(path: String, queryItems: [URLQueryItem] = []) -> URL {
2021-12-08 02:58:02 +00:00
var components = URLComponents(url: instanceURL, resolvingAgainstBaseURL: false)!
components.path = path
2022-01-09 22:13:30 +00:00
components.queryItems = queryItems
2021-12-08 02:58:02 +00:00
return components.url!
}
private func performRequest<T: Decodable>(_ request: URLRequest) async throws -> T {
var request = request
if let accessToken = accessToken {
request.addValue("Bearer \(accessToken)", forHTTPHeaderField: "Authorization")
}
2022-01-09 22:13:30 +00:00
let (data, response) = try await session.data(for: request, delegate: nil)
if (response as! HTTPURLResponse).statusCode == 404 {
throw Error.notFound
}
2021-12-08 02:58:02 +00:00
let decoded = try decoder.decode(T.self, from: data)
return decoded
}
public func register(clientName: String, website: URL? = nil, redirectURI: URL) async throws -> ClientRegistration {
var request = URLRequest(url: buildURL(path: "/api/v1/register"))
request.httpMethod = "POST"
request.setURLEncodedBody(params: [
"client_name": clientName,
"website": website?.absoluteString,
"redirect_uri": redirectURI.absoluteString,
])
return try await performRequest(request)
}
public func token(authCode: String, redirectURI: URL, clientID: String, clientSecret: String) async throws -> Token {
var request = URLRequest(url: buildURL(path: "/oauth/token"))
request.httpMethod = "POST"
request.setURLEncodedBody(params: [
"grant_type": "authorization_code",
"authorization_code": authCode,
"redirect_uri": redirectURI.absoluteString,
"client_id": clientID,
"client_secret": clientSecret,
])
return try await performRequest(request)
}
2021-12-25 19:04:45 +00:00
public func groups() async throws -> [Group] {
let request = URLRequest(url: buildURL(path: "/api/v1/groups"))
return try await performRequest(request)
}
public func feeds() async throws -> [Feed] {
let request = URLRequest(url: buildURL(path: "/api/v1/feeds"))
return try await performRequest(request)
}
2022-01-09 22:13:30 +00:00
public func syncItems(lastSync: Date?) async throws -> ItemsSyncUpdate {
let request = URLRequest(url: buildURL(path: "/api/v1/items/sync", queryItems: [
URLQueryItem(name: "last_sync", value: lastSync?.formatted(.iso8601))
]))
return try await performRequest(request)
}
public func items(feed id: FervorID) async throws -> [Item] {
let request = URLRequest(url: buildURL(path: "/api/v1/feeds/\(id)/items"))
return try await performRequest(request)
}
public func item(id: FervorID) async throws -> Item? {
let request = URLRequest(url: buildURL(path: "/api/v1/items/\(id)"))
do {
return try await performRequest(request)
} catch {
if let error = error as? Error, case .notFound = error {
return nil
} else {
throw error
}
}
}
2022-01-11 16:54:57 +00:00
public func read(item id: FervorID) async throws -> Item {
var request = URLRequest(url: buildURL(path: "/api/v1/items/\(id)/read"))
request.httpMethod = "POST"
return try await performRequest(request)
}
public func unread(item id: FervorID) async throws -> Item {
var request = URLRequest(url: buildURL(path: "/api/v1/items/\(id)/unread"))
request.httpMethod = "POST"
return try await performRequest(request)
}
2021-12-08 02:58:02 +00:00
public struct Auth {
public let accessToken: String
public let refreshToken: String?
}
public enum Error: Swift.Error {
case urlSession(Swift.Error)
case decode(Swift.Error)
2022-01-09 22:13:30 +00:00
case notFound
2021-12-08 02:58:02 +00:00
}
}
2022-01-09 22:13:30 +00:00
private struct DateDecodingError: Error {
}