2023-12-13 15:07:16 +01:00
|
|
|
// Copyright © 2023 Mastodon gGmbH. All rights reserved.
|
|
|
|
|
|
|
|
import Foundation
|
|
|
|
import MastodonSDK
|
|
|
|
|
2023-12-28 22:39:24 +01:00
|
|
|
public extension FileManager {
|
|
|
|
func store(account: Mastodon.Entity.Account, forUserID userID: UserIdentifier) {
|
|
|
|
var accounts = accounts(for: userID)
|
2023-12-13 15:07:16 +01:00
|
|
|
|
|
|
|
if let index = accounts.firstIndex(of: account) {
|
|
|
|
accounts.remove(at: index)
|
|
|
|
}
|
|
|
|
|
|
|
|
accounts.append(account)
|
|
|
|
|
|
|
|
storeJSON(accounts, userID: userID)
|
|
|
|
}
|
|
|
|
|
2023-12-28 22:39:24 +01:00
|
|
|
func accounts(for userId: UserIdentifier) -> [Mastodon.Entity.Account] {
|
2024-01-02 23:05:25 +01:00
|
|
|
guard let sharedDirectory else { return [] }
|
2023-12-13 15:07:16 +01:00
|
|
|
|
2024-01-02 23:05:25 +01:00
|
|
|
let accountPath = Persistence.accounts(userId).filepath(baseURL: sharedDirectory)
|
2023-12-13 15:07:16 +01:00
|
|
|
|
|
|
|
guard let data = try? Data(contentsOf: accountPath) else { return [] }
|
|
|
|
|
|
|
|
let jsonDecoder = JSONDecoder()
|
|
|
|
jsonDecoder.dateDecodingStrategy = .iso8601
|
|
|
|
|
|
|
|
do {
|
|
|
|
let accounts = try jsonDecoder.decode([Mastodon.Entity.Account].self, from: data)
|
|
|
|
return accounts
|
|
|
|
} catch {
|
|
|
|
return []
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
2023-12-28 22:39:24 +01:00
|
|
|
}
|
2023-12-13 15:07:16 +01:00
|
|
|
|
2023-12-28 22:39:24 +01:00
|
|
|
private extension FileManager {
|
|
|
|
private func storeJSON(_ encodable: Encodable, userID: UserIdentifier) {
|
2024-01-02 23:05:25 +01:00
|
|
|
guard let sharedDirectory else { return }
|
2023-12-13 15:07:16 +01:00
|
|
|
|
|
|
|
let jsonEncoder = JSONEncoder()
|
|
|
|
jsonEncoder.dateEncodingStrategy = .iso8601
|
|
|
|
do {
|
|
|
|
let data = try jsonEncoder.encode(encodable)
|
|
|
|
|
2024-01-02 23:05:25 +01:00
|
|
|
let accountsPath = Persistence.accounts( userID).filepath(baseURL: sharedDirectory)
|
2023-12-13 15:07:16 +01:00
|
|
|
try data.write(to: accountsPath)
|
|
|
|
} catch {
|
|
|
|
debugPrint(error.localizedDescription)
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|