2021-02-23 12:18:34 +01:00
|
|
|
//
|
|
|
|
// MosaicImageViewModel.swift
|
|
|
|
// Mastodon
|
|
|
|
//
|
|
|
|
// Created by Cirno MainasuK on 2021-2-23.
|
|
|
|
//
|
|
|
|
|
|
|
|
import UIKit
|
2021-04-16 14:06:36 +02:00
|
|
|
import Combine
|
2021-02-23 12:18:34 +01:00
|
|
|
import CoreDataStack
|
|
|
|
|
|
|
|
struct MosaicImageViewModel {
|
|
|
|
|
|
|
|
let metas: [MosaicMeta]
|
|
|
|
|
|
|
|
init(mediaAttachments: [Attachment]) {
|
|
|
|
var metas: [MosaicMeta] = []
|
|
|
|
for element in mediaAttachments where element.type == .image {
|
|
|
|
// Display original on the iPad/Mac
|
2021-03-08 04:21:34 +01:00
|
|
|
guard let previewURL = element.previewURL else { continue }
|
|
|
|
let urlString = UIDevice.current.userInterfaceIdiom == .phone ? previewURL : element.url
|
2021-02-23 12:18:34 +01:00
|
|
|
guard let meta = element.meta,
|
|
|
|
let width = meta.original?.width,
|
|
|
|
let height = meta.original?.height,
|
|
|
|
let url = URL(string: urlString) else {
|
|
|
|
continue
|
|
|
|
}
|
2021-04-16 14:06:36 +02:00
|
|
|
let mosaicMeta = MosaicMeta(
|
|
|
|
url: url,
|
|
|
|
size: CGSize(width: width, height: height),
|
|
|
|
blurhash: element.blurhash
|
|
|
|
)
|
|
|
|
metas.append(mosaicMeta)
|
2021-02-23 12:18:34 +01:00
|
|
|
}
|
|
|
|
self.metas = metas
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
struct MosaicMeta {
|
2021-04-16 14:06:36 +02:00
|
|
|
static let edgeMaxLength: CGFloat = 20
|
|
|
|
|
2021-02-23 12:18:34 +01:00
|
|
|
let url: URL
|
|
|
|
let size: CGSize
|
2021-04-16 14:06:36 +02:00
|
|
|
let blurhash: String?
|
|
|
|
|
|
|
|
let workingQueue = DispatchQueue(label: "org.joinmastodon.Mastodon.MosaicMeta.working-queue", qos: .userInitiated, attributes: .concurrent)
|
|
|
|
|
|
|
|
func blurhashImagePublisher() -> AnyPublisher<UIImage?, Never> {
|
|
|
|
return Future { promise in
|
|
|
|
guard let blurhash = blurhash else {
|
|
|
|
promise(.success(nil))
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
let imageSize: CGSize = {
|
|
|
|
let aspectRadio = size.width / size.height
|
|
|
|
if size.width > size.height {
|
|
|
|
let width: CGFloat = MosaicMeta.edgeMaxLength
|
|
|
|
let height = width / aspectRadio
|
|
|
|
return CGSize(width: width, height: height)
|
|
|
|
} else {
|
|
|
|
let height: CGFloat = MosaicMeta.edgeMaxLength
|
|
|
|
let width = height * aspectRadio
|
|
|
|
return CGSize(width: width, height: height)
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
workingQueue.async {
|
|
|
|
let image = UIImage(blurHash: blurhash, size: imageSize)
|
|
|
|
promise(.success(image))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
.eraseToAnyPublisher()
|
|
|
|
}
|
2021-02-23 12:18:34 +01:00
|
|
|
}
|