Impressia/Vernissage/Views/ComposeView.swift

72 lines
2.3 KiB
Swift
Raw Normal View History

2023-01-06 18:16:08 +01:00
//
// https://mczachurski.dev
// Copyright © 2023 Marcin Czachurski and the repository contributors.
2023-03-28 10:35:38 +02:00
// Licensed under the Apache License 2.0.
2023-01-06 18:16:08 +01:00
//
2023-01-06 18:16:08 +01:00
import SwiftUI
2023-02-14 18:40:08 +01:00
import PhotosUI
2023-02-19 10:32:38 +01:00
import PixelfedKit
2023-04-07 14:20:12 +02:00
import ClientKit
import UIKit
2023-04-07 14:38:50 +02:00
import ServicesKit
2023-04-07 16:59:18 +02:00
import EnvironmentKit
import WidgetsKit
2023-01-06 18:16:08 +01:00
struct ComposeView: View {
2023-02-17 14:47:59 +01:00
@EnvironmentObject var routerPath: RouterPath
2023-02-03 15:16:30 +01:00
@EnvironmentObject var client: Client
2023-02-17 14:47:59 +01:00
2023-01-06 18:16:08 +01:00
@Environment(\.dismiss) private var dismiss
2023-02-27 16:04:42 +01:00
private let statusViewModel: StatusModel?
2023-02-27 14:03:22 +01:00
public init(statusViewModel: StatusModel? = nil) {
self.statusViewModel = statusViewModel
}
2023-01-06 18:16:08 +01:00
var body: some View {
NavigationView {
BaseComposeView(statusViewModel: self.statusViewModel) {
dismiss()
} onUpload: { photoAttachment in
await self.upload(photoAttachment)
2023-02-27 16:04:42 +01:00
}
.navigationTitle("compose.navigationBar.title")
.navigationBarTitleDisplayMode(.inline)
2023-02-21 21:54:10 +01:00
}
.withOverlayDestinations(overlayDestinations: $routerPath.presentedOverlay)
2023-02-21 21:54:10 +01:00
}
2023-02-21 21:54:10 +01:00
private func upload(_ photoAttachment: PhotoAttachment) async {
do {
// Image shouldn't be uploaded yet.
guard photoAttachment.uploadedAttachment == nil else {
2023-02-22 20:49:08 +01:00
return
}
// We are sending orginal file (not file compressed from memory).
2023-04-11 07:37:05 +02:00
guard let photoUrl = photoAttachment.photoUrl,
let data = try? Data(contentsOf: photoUrl),
let uiImage = UIImage(data: data) else {
return
}
// Compresing to JPEG with extendedRGB color space.
guard let data = uiImage.getJpegData() else {
return
}
2023-02-21 21:54:10 +01:00
let fileIndex = String.randomString(length: 8)
if let mediaAttachment = try await self.client.media?.upload(data: data,
2023-02-21 21:54:10 +01:00
fileName: "file-\(fileIndex).jpg",
mimeType: "image/jpeg") {
photoAttachment.uploadedAttachment = mediaAttachment
2023-02-17 12:21:09 +01:00
}
2023-02-21 21:54:10 +01:00
} catch {
photoAttachment.uploadError = error
2023-03-13 13:53:36 +01:00
ErrorService.shared.handle(error, message: "compose.error.postingPhotoFailed", showToastr: true)
2023-02-17 12:21:09 +01:00
}
}
2023-01-06 18:16:08 +01:00
}