Tusker/Tusker/MastodonCache.swift

114 lines
3.3 KiB
Swift

//
// StatusCache.swift
// Tusker
//
// Created by Shadowfacts on 9/17/18.
// Copyright © 2018 Shadowfacts. All rights reserved.
//
import Foundation
import Pachyderm
class MastodonCache {
// private static let statuses = NSDictionary<NSString, Status>()
// private static let accounts = NSDictionary<NSString, Account>()
// private static let relationships = NSCache<NSString, Relationship>()
private static var statuses = [String: Status]()
private static var accounts = [String: Account]()
private static var relationships = [String: Relationship]()
// MARK: - Statuses
static func status(for id: String) -> Status? {
return statuses[id]
}
static func set(status: Status, for id: String) {
statuses[id] = status
add(account: status.account)
if let reblog = status.reblog {
add(account: reblog.account)
}
}
static func status(for id: String, completion: @escaping (Status?) -> Void) {
let request = MastodonController.client.getStatus(id: id)
MastodonController.client.run(request) { response in
guard case let .success(status, _) = response else {
completion(nil)
return
}
set(status: status, for: id)
completion(status)
}
}
static func add(status: Status) {
set(status: status, for: status.id)
}
static func addAll(statuses: [Status]) {
statuses.forEach(add)
}
// MARK: - Accounts
static func account(for id: String) -> Account? {
return accounts[id]
}
static func set(account: Account, for id: String) {
accounts[id] = account
}
static func account(for id: String, completion: @escaping (Account?) -> Void) {
let request = MastodonController.client.getAccount(id: id)
MastodonController.client.run(request) { response in
guard case let .success(account, _) = response else {
completion(nil)
return
}
set(account: account, for: account.id)
completion(account)
}
}
static func add(account: Account) {
set(account: account, for: account.id)
}
static func addAll(accounts: [Account]) {
accounts.forEach(add)
}
// MARK: - Relationships
static func relationship(for id: String) -> Relationship? {
return relationships[id]
}
static func set(relationship: Relationship, id: String) {
relationships[id] = relationship
}
static func relationship(for id: String, completion: @escaping (Relationship?) -> Void) {
let request = MastodonController.client.getRelationships(accounts: [id])
MastodonController.client.run(request) { response in
guard case let .success(relationships, _) = response,
let relationship = relationships.first else {
completion(nil)
return
}
set(relationship: relationship, id: relationship.id)
completion(relationship)
}
}
static func add(relationship: Relationship) {
set(relationship: relationship, id: relationship.id)
}
static func addAll(relationships: [Relationship]) {
relationships.forEach(add)
}
}