NetNewsWire/Frameworks/Account/NewsBlur/NewsBlurAPICaller.swift

267 lines
7.8 KiB
Swift
Raw Normal View History

2020-03-10 01:19:24 +01:00
//
// NewsBlurAPICaller.swift
// Account
//
// Created by Anh-Quang Do on 3/9/20.
// Copyright (c) 2020 Ranchero Software, LLC. All rights reserved.
//
import Foundation
import RSWeb
enum NewsBlurError: LocalizedError {
case general(message: String)
2020-03-15 01:00:29 +01:00
case invalidParameter
2020-03-14 04:16:52 +01:00
case unknown
2020-03-10 01:19:24 +01:00
var errorDescription: String? {
switch self {
case .general(let message):
return message
2020-03-15 01:00:29 +01:00
case .invalidParameter:
return "There was an invalid parameter passed"
2020-03-14 04:16:52 +01:00
case .unknown:
return "An unknown error occurred"
2020-03-10 01:19:24 +01:00
}
}
}
final class NewsBlurAPICaller: NSObject {
2020-03-10 04:26:11 +01:00
static let SessionIdCookie = "newsblur_sessionid"
2020-03-10 01:19:24 +01:00
private let baseURL = URL(string: "https://www.newsblur.com/")!
private var transport: Transport!
2020-03-14 03:23:54 +01:00
private var suspended = false
2020-03-10 01:19:24 +01:00
var credentials: Credentials?
weak var accountMetadata: AccountMetadata?
init(transport: Transport!) {
super.init()
self.transport = transport
}
2020-03-14 03:23:54 +01:00
/// Cancels all pending requests rejects any that come in later
func suspend() {
transport.cancelAll()
suspended = true
}
func resume() {
suspended = false
}
2020-03-10 01:19:24 +01:00
func validateCredentials(completion: @escaping (Result<Credentials?, Error>) -> Void) {
let url = baseURL.appendingPathComponent("api/login")
let request = URLRequest(url: url, credentials: credentials)
transport.send(request: request, resultType: NewsBlurLoginResponse.self) { result in
2020-03-14 03:23:54 +01:00
if self.suspended {
completion(.failure(TransportError.suspended))
return
}
2020-03-10 01:19:24 +01:00
switch result {
2020-03-10 04:26:11 +01:00
case .success(let response, let payload):
guard let url = response.url, let headerFields = response.allHeaderFields as? [String: String], payload?.code != -1 else {
2020-03-10 01:19:24 +01:00
let error = payload?.errors?.username ?? payload?.errors?.others
if let message = error?.first {
completion(.failure(NewsBlurError.general(message: message)))
} else {
2020-03-15 01:00:29 +01:00
completion(.failure(NewsBlurError.unknown))
2020-03-10 01:19:24 +01:00
}
return
}
2020-03-10 04:26:11 +01:00
guard let username = self.credentials?.username else {
2020-03-15 01:00:29 +01:00
completion(.failure(NewsBlurError.unknown))
2020-03-10 04:26:11 +01:00
return
}
let cookies = HTTPCookie.cookies(withResponseHeaderFields: headerFields, for: url)
for cookie in cookies where cookie.name == Self.SessionIdCookie {
let credentials = Credentials(type: .newsBlurSessionId, username: username, secret: cookie.value)
completion(.success(credentials))
return
}
completion(.failure(NewsBlurError.general(message: "Failed to retrieve session")))
2020-03-10 01:19:24 +01:00
case .failure(let error):
completion(.failure(error))
}
}
}
func logout(completion: @escaping (Result<Void, Error>) -> Void) {
let url = baseURL.appendingPathComponent("api/logout")
let request = URLRequest(url: url, credentials: credentials)
transport.send(request: request) { result in
2020-03-14 03:23:54 +01:00
if self.suspended {
completion(.failure(TransportError.suspended))
return
}
2020-03-10 01:19:24 +01:00
switch result {
case .success:
completion(.success(()))
case .failure(let error):
completion(.failure(error))
}
}
}
2020-03-10 04:26:48 +01:00
func retrieveFeeds(completion: @escaping (Result<([NewsBlurFeed]?, [NewsBlurFolder]?), Error>) -> Void) {
2020-03-10 04:26:48 +01:00
let url = baseURL
.appendingPathComponent("reader/feeds")
.appendingQueryItems([
URLQueryItem(name: "flat", value: "true"),
URLQueryItem(name: "update_counts", value: "false"),
])
guard let callURL = url else {
completion(.failure(TransportError.noURL))
return
}
let request = URLRequest(url: callURL, credentials: credentials)
transport.send(request: request, resultType: NewsBlurFeedsResponse.self) { result in
2020-03-14 03:23:54 +01:00
if self.suspended {
completion(.failure(TransportError.suspended))
return
}
2020-03-10 04:26:48 +01:00
switch result {
2020-03-11 02:08:56 +01:00
case .success((_, let payload)):
completion(.success((payload?.feeds, payload?.folders)))
2020-03-11 02:08:56 +01:00
case .failure(let error):
completion(.failure(error))
}
}
}
func retrieveUnreadStoryHashes(completion: @escaping (Result<[NewsBlurStoryHash]?, Error>) -> Void) {
2020-03-14 21:10:05 +01:00
retrieveStoryHashes(endpoint: "reader/unread_story_hashes", completion: completion)
}
2020-03-14 03:23:54 +01:00
2020-03-14 21:10:05 +01:00
func retrieveStarredStoryHashes(completion: @escaping (Result<[NewsBlurStoryHash]?, Error>) -> Void) {
retrieveStoryHashes(endpoint: "reader/starred_story_hashes", completion: completion)
2020-03-13 23:18:47 +01:00
}
func retrieveStories(hashes: [NewsBlurStoryHash], completion: @escaping (Result<[NewsBlurStory]?, Error>) -> Void) {
2020-03-13 23:18:47 +01:00
let url = baseURL
.appendingPathComponent("reader/river_stories")
.appendingQueryItem(.init(name: "include_hidden", value: "true"))?
2020-03-14 21:10:05 +01:00
.appendingQueryItems(hashes.map {
URLQueryItem(name: "h", value: $0.hash)
})
2020-03-13 23:18:47 +01:00
guard let callURL = url else {
completion(.failure(TransportError.noURL))
return
}
let request = URLRequest(url: callURL, credentials: credentials)
transport.send(request: request, resultType: NewsBlurStoriesResponse.self) { result in
2020-03-14 03:23:54 +01:00
if self.suspended {
completion(.failure(TransportError.suspended))
return
}
2020-03-13 23:18:47 +01:00
switch result {
case .success((_, let payload)):
completion(.success(payload?.stories))
2020-03-10 04:26:48 +01:00
case .failure(let error):
completion(.failure(error))
}
}
}
2020-03-14 04:16:52 +01:00
func markAsUnread(hashes: [String], completion: @escaping (Result<Void, Error>) -> Void) {
sendStoryStatus(endpoint: "reader/mark_story_hash_as_unread", hashes: hashes, completion: completion)
}
func markAsRead(hashes: [String], completion: @escaping (Result<Void, Error>) -> Void) {
sendStoryStatus(endpoint: "reader/mark_story_hashes_as_read", hashes: hashes, completion: completion)
}
func star(hashes: [String], completion: @escaping (Result<Void, Error>) -> Void) {
sendStoryStatus(endpoint: "reader/mark_story_hash_as_starred", hashes: hashes, completion: completion)
}
func unstar(hashes: [String], completion: @escaping (Result<Void, Error>) -> Void) {
sendStoryStatus(endpoint: "reader/mark_story_hash_as_unstarred", hashes: hashes, completion: completion)
}
2020-03-15 01:00:29 +01:00
func addFolder(named name: String, completion: @escaping (Result<Void, Error>) -> Void) {
let callURL = baseURL.appendingPathComponent("reader/add_folder")
var request = URLRequest(url: callURL, credentials: credentials)
request.httpBody = NewsBlurFolderChange.add(name).asData
transport.send(request: request, method: HTTPMethod.post) { result in
if self.suspended {
completion(.failure(TransportError.suspended))
return
}
switch result {
case .success:
completion(.success(()))
case .failure(let error):
completion(.failure(error))
}
}
}
2020-03-14 21:10:05 +01:00
}
extension NewsBlurAPICaller {
private func retrieveStoryHashes(endpoint: String, completion: @escaping (Result<[NewsBlurStoryHash]?, Error>) -> Void) {
let url = baseURL
.appendingPathComponent(endpoint)
.appendingQueryItems([
URLQueryItem(name: "include_timestamps", value: "true"),
])
guard let callURL = url else {
completion(.failure(TransportError.noURL))
return
}
let request = URLRequest(url: callURL, credentials: credentials)
transport.send(request: request, resultType: NewsBlurStoryHashesResponse.self, dateDecoding: .secondsSince1970) { result in
2020-03-14 21:10:05 +01:00
if self.suspended {
completion(.failure(TransportError.suspended))
return
}
switch result {
case .success((_, let payload)):
let hashes = payload?.unread ?? payload?.starred
completion(.success(hashes?.values.flatMap { $0 }))
2020-03-14 21:10:05 +01:00
case .failure(let error):
completion(.failure(error))
}
}
}
2020-03-14 04:16:52 +01:00
private func sendStoryStatus(endpoint: String, hashes: [String], completion: @escaping (Result<Void, Error>) -> Void) {
let callURL = baseURL.appendingPathComponent(endpoint)
var request = URLRequest(url: callURL, credentials: credentials)
request.httpBody = NewsBlurStoryStatusChange(hashes: hashes).asData
transport.send(request: request, method: HTTPMethod.post) { result in
if self.suspended {
completion(.failure(TransportError.suspended))
return
}
switch result {
case .success:
completion(.success(()))
case .failure(let error):
completion(.failure(error))
}
}
}
2020-03-10 01:19:24 +01:00
}