mastodon-ios/Mastodon/Protocol/Provider/DataSourceFacade+Translate....

70 lines
2.0 KiB
Swift
Raw Normal View History

//
// DataSourceFacade+Translate.swift
// Mastodon
//
// Created by Marcus Kida on 29.11.22.
//
import UIKit
import CoreData
import CoreDataStack
import MastodonCore
typealias Provider = UIViewController & NeedsDependency & AuthContextProvider
extension DataSourceFacade {
enum TranslationFailure: Error {
case emptyOrInvalidResponse
}
public static func translateStatus(
provider: Provider,
status: ManagedObjectRecord<Status>
) async throws {
let selectionFeedbackGenerator = await UISelectionFeedbackGenerator()
await selectionFeedbackGenerator.selectionChanged()
2022-12-02 12:12:46 +01:00
guard
let status = status.object(in: provider.context.managedObjectContext)
else {
return
}
if let reblog = status.reblog {
try await translateAndApply(provider: provider, status: reblog)
} else {
try await translateAndApply(provider: provider, status: status)
}
}
}
private extension DataSourceFacade {
static func translateStatus(provider: Provider, status: Status) async throws -> String? {
do {
let value = try await provider.context
.apiService
.translateStatus(
statusID: status.id,
authenticationBox: provider.authContext.mastodonAuthenticationBox
).value
guard let content = value.content else {
throw TranslationFailure.emptyOrInvalidResponse
}
return content
} catch {
throw TranslationFailure.emptyOrInvalidResponse
}
}
static func translateAndApply(provider: Provider, status: Status) async throws {
do {
status.translatedContent = try await translateStatus(provider: provider, status: status)
} catch {
status.translatedContent = nil
throw TranslationFailure.emptyOrInvalidResponse
2022-12-02 14:42:50 +01:00
}
}
}