Tusker/Tusker/Views/Status/StatusTableViewCell.swift

382 wiersze
16 KiB
Swift

//
// StatusTableViewCell.swift
// Tusker
//
// Created by Shadowfacts on 8/16/18.
// Copyright © 2018 Shadowfacts. All rights reserved.
//
import UIKit
import Pachyderm
protocol StatusTableViewCellDelegate: TuskerNavigationDelegate {
}
class StatusTableViewCell: UITableViewCell, PreferencesAdaptive {
var delegate: StatusTableViewCellDelegate? {
didSet {
contentLabel.navigationDelegate = delegate
}
}
@IBOutlet weak var displayNameLabel: UILabel!
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var contentLabel: StatusContentLabel!
@IBOutlet weak var avatarImageView: UIImageView!
@IBOutlet weak var reblogLabel: UILabel!
@IBOutlet weak var timestampLabel: UILabel!
@IBOutlet weak var attachmentsView: UIView!
@IBOutlet weak var favoriteButton: UIButton!
@IBOutlet weak var reblogButton: UIButton!
var statusID: String!
var accountID: String!
var reblogStatusID: String?
var rebloggerID: String?
var favorited: Bool = false {
didSet {
favoriteButton.tintColor = favorited ? UIColor(displayP3Red: 1, green: 0.8, blue: 0, alpha: 1) : tintColor
}
}
var reblogged: Bool = false {
didSet {
reblogButton.tintColor = reblogged ? UIColor(displayP3Red: 1, green: 0.8, blue: 0, alpha: 1) : tintColor
}
}
var avatarURL: URL?
var updateTimestampWorkItem: DispatchWorkItem?
var attachmentDataTasks: [URLSessionDataTask] = []
override func awakeFromNib() {
displayNameLabel.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(accountPressed)))
displayNameLabel.isUserInteractionEnabled = true
usernameLabel.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(accountPressed)))
usernameLabel.isUserInteractionEnabled = true
reblogLabel.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(reblogLabelPressed)))
reblogLabel.isUserInteractionEnabled = true
avatarImageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(accountPressed)))
avatarImageView.isUserInteractionEnabled = true
avatarImageView.layer.masksToBounds = true
attachmentsView.layer.cornerRadius = 5
attachmentsView.layer.masksToBounds = true
}
func updateUIForPreferences() {
guard let account = MastodonCache.account(for: accountID) else { fatalError("") }
avatarImageView.layer.cornerRadius = Preferences.shared.avatarStyle.cornerRadius(for: avatarImageView)
if let rebloggerID = rebloggerID,
let reblogger = MastodonCache.account(for: rebloggerID) {
reblogLabel.text = "Reblogged by \(reblogger.realDisplayName)"
}
displayNameLabel.text = account.realDisplayName
}
func updateUI(for statusID: String) {
guard var status = MastodonCache.status(for: statusID) else { fatalError("Missing cached status \(statusID)") }
if let reblogID = status.reblog?.id,
let reblog = MastodonCache.status(for: reblogID) {
reblogStatusID = statusID
rebloggerID = status.account.id
status = reblog
reblogLabel.isHidden = false
} else {
reblogStatusID = nil
rebloggerID = nil
reblogLabel.isHidden = true
}
let account = status.account
self.accountID = account.id
self.statusID = status.id
updateUIForPreferences()
usernameLabel.text = "@\(account.acct)"
avatarImageView.image = nil
avatarURL = account.avatar
ImageCache.avatars.get(account.avatar) { (data) in
guard let data = data else { return }
DispatchQueue.main.async {
self.avatarImageView.image = UIImage(data: data)
self.avatarURL = nil
}
}
updateTimestamp()
let attachments = status.attachments.filter({ $0.kind == .image })
if attachments.count > 0 {
attachmentsView.isHidden = false
let width = attachmentsView.bounds.width
let height: CGFloat = 200
switch attachments.count {
case 1:
addAttachmentView(frame: CGRect(x: 0, y: 0, width: width, height: height), attachment: attachments[0])
case 2:
addAttachmentView(frame: CGRect(x: 0, y: 0, width: width / 2 - 4, height: height), attachment: attachments[0])
addAttachmentView(frame: CGRect(x: width / 2 + 4, y: 0, width: width / 2 - 4, height: height), attachment: attachments[1])
case 3:
addAttachmentView(frame: CGRect(x: 0, y: 0, width: width / 2 - 4, height: height), attachment: attachments[0])
addAttachmentView(frame: CGRect(x: width / 2 + 4, y: 0, width: width / 2 - 4, height: height / 2 - 4), attachment: attachments[1])
addAttachmentView(frame: CGRect(x: width / 2 + 4, y: height / 2 + 4, width: width / 2 - 4, height: height / 2 - 4), attachment: attachments[2])
case 4:
addAttachmentView(frame: CGRect(x: 0, y: 0, width: width / 2 - 4, height: height / 2 - 4), attachment: attachments[0])
addAttachmentView(frame: CGRect(x: 0, y: height / 2 + 4, width: width / 2 - 4, height: height / 2 - 4), attachment: attachments[1])
addAttachmentView(frame: CGRect(x: width / 2 + 4, y: 0, width: width / 2 - 4, height: height / 2 - 4), attachment: attachments[2])
addAttachmentView(frame: CGRect(x: width / 2 + 4, y: height / 2 + 4, width: width / 2 - 4, height: height / 2 - 4), attachment: attachments[3])
default:
fatalError("Too many attachments")
}
} else {
attachmentsView.isHidden = true
}
let realStatus = status.reblog ?? status
favorited = realStatus.favourited ?? false
reblogged = realStatus.reblogged ?? false
contentLabel.statusID = statusID
}
func updateTimestamp() {
guard let status = MastodonCache.status(for: statusID) else { fatalError("Missing cached status \(statusID!)") }
timestampLabel.text = status.createdAt.timeAgoString()
let delay: DispatchTimeInterval?
switch status.createdAt.timeAgo().1 {
case .second:
delay = .seconds(10)
case .minute:
delay = .seconds(60)
default:
delay = nil
}
if let delay = delay {
updateTimestampWorkItem = DispatchWorkItem {
self.updateTimestamp()
}
DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: updateTimestampWorkItem!)
} else {
updateTimestampWorkItem = nil
}
}
func addAttachmentView(frame: CGRect, attachment: Attachment) {
let attachmentView = AttachmentView(frame: frame, attachment: attachment)
attachmentView.delegate = self
attachmentsView.addSubview(attachmentView)
}
override func prepareForReuse() {
if let url = avatarURL {
ImageCache.avatars.cancel(url)
}
updateTimestampWorkItem?.cancel()
updateTimestampWorkItem = nil
attachmentsView.subviews.forEach { $0.removeFromSuperview() }
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
if selected {
delegate?.selected(status: statusID)
}
}
@IBAction func replyPressed(_ sender: Any) {
delegate?.reply(to: statusID)
}
@objc func accountPressed() {
delegate?.selected(account: accountID)
}
@objc func reblogLabelPressed() {
guard let rebloggerID = rebloggerID else { return }
delegate?.selected(account: rebloggerID)
}
@IBAction func favoritePressed(_ sender: Any) {
guard let status = MastodonCache.status(for: statusID) else { fatalError("Missing cached status \(statusID!)") }
let oldValue = favorited
favorited = !favorited
let realStatus: Status = status.reblog ?? status
let request = (favorited ? Status.favourite : Status.unfavourite)(realStatus)
MastodonController.client.run(request) { response in
DispatchQueue.main.async {
self.favorited = realStatus.favourited ?? false
if case .success = response {
self.favorited = realStatus.favourited ?? false
UIImpactFeedbackGenerator(style: .light).impactOccurred()
} else {
self.favorited = oldValue
print("Couldn't favorite status \(realStatus.id)")
// todo: display error message
UINotificationFeedbackGenerator().notificationOccurred(.error)
return
}
}
}
}
@IBAction func reblogPressed(_ sender: Any) {
guard let status = MastodonCache.status(for: statusID) else { fatalError("Missing cached status \(statusID!)") }
let oldValue = reblogged
reblogged = !reblogged
let realStatus: Status = status.reblog ?? status
let request = (reblogged ? Status.reblog : Status.unreblog)(realStatus)
MastodonController.client.run(request) { response in
self.reblogged = realStatus.reblogged ?? false
DispatchQueue.main.async {
if case .success = response {
self.reblogged = realStatus.reblogged ?? false
UIImpactFeedbackGenerator(style: .light).impactOccurred()
} else {
self.reblogged = oldValue
print("Couldn't reblog status \(realStatus.id)")
// todo: display error message
UINotificationFeedbackGenerator().notificationOccurred(.error)
}
}
}
}
@IBAction func morePressed(_ sender: Any) {
delegate?.showMoreOptions(forStatus: statusID)
}
}
extension StatusTableViewCell: TableViewSwipeActionProvider {
static var favoriteActionImage: UIImage = UIGraphicsImageRenderer(size: CGSize(width: 30 * 137/131, height: 30)).image { _ in
UIImage(named: "Favorite")!.draw(in: CGRect(x: 0, y: 0, width: 30 * 137/131, height: 30))
}
static var reblogActionImage: UIImage = UIGraphicsImageRenderer(size: CGSize(width: 30 * 927/558, height: 30)).image { _ in
UIImage(named: "Reblog")!.draw(in: CGRect(x: 0, y: 0, width: 30 * 927/558, height: 30))
}
static var replyActionImage: UIImage = UIGraphicsImageRenderer(size: CGSize(width: 30 * 205/151, height: 30)).image { _ in
UIImage(named: "Reply")!.draw(in: CGRect(x: 0, y: 0, width: 30 * 205/151, height: 30))
}
static var moreActionImage: UIImage = UIGraphicsImageRenderer(size: CGSize(width: 30 * 2/1, height: 30)).image { _ in
UIImage(named: "More")!.draw(in: CGRect(x: 0, y: 0, width: 30 * 2/1, height: 30))
}
func leadingSwipeActionsConfiguration() -> UISwipeActionsConfiguration? {
guard let status = MastodonCache.status(for: statusID) else { fatalError("Missing cached status \(statusID!)") }
let favoriteTitle: String
let favoriteRequest: Request<Status>
let favoriteColor: UIColor
if status.favourited ?? false {
favoriteTitle = "Unfavorite"
favoriteRequest = Status.unfavourite(status)
favoriteColor = UIColor(displayP3Red: 235/255, green: 77/255, blue: 62/255, alpha: 1)
} else {
favoriteTitle = "Favorite"
favoriteRequest = Status.favourite(status)
favoriteColor = UIColor(displayP3Red: 1, green: 204/255, blue: 0, alpha: 1)
}
let favorite = UIContextualAction(style: .normal, title: favoriteTitle) { (action, view, completion) in
MastodonController.client.run(favoriteRequest, completion: { response in
DispatchQueue.main.async {
guard case let .success(status, _) = response else {
completion(false)
return
}
completion(true)
MastodonCache.add(status: status)
self.updateUI(for: self.reblogStatusID ?? self.statusID)
}
})
}
favorite.image = StatusTableViewCell.favoriteActionImage
favorite.backgroundColor = favoriteColor
let reblogTitle: String
let reblogRequest: Request<Status>
let reblogColor: UIColor
if status.reblogged ?? false {
reblogTitle = "Unreblog"
reblogRequest = Status.unreblog(status)
reblogColor = UIColor(displayP3Red: 235/255, green: 77/255, blue: 62/255, alpha: 1)
} else {
reblogTitle = "Reblog"
reblogRequest = Status.reblog(status)
reblogColor = tintColor
}
let reblog = UIContextualAction(style: .normal, title: reblogTitle) { (action, view, completion) in
MastodonController.client.run(reblogRequest, completion: { response in
DispatchQueue.main.async {
guard case let .success(status, _) = response else {
completion(false)
return
}
completion(true)
MastodonCache.add(status: status)
self.updateUI(for: self.reblogStatusID ?? self.statusID)
}
})
}
reblog.image = StatusTableViewCell.reblogActionImage
reblog.backgroundColor = reblogColor
return UISwipeActionsConfiguration(actions: [favorite, reblog])
}
func trailingSwipeActionsConfiguration() -> UISwipeActionsConfiguration? {
let reply = UIContextualAction(style: .normal, title: "Reply") { (action, view, completion) in
completion(true)
self.delegate?.reply(to: self.statusID)
}
reply.image = StatusTableViewCell.replyActionImage
reply.backgroundColor = tintColor
let more = UIContextualAction(style: .normal, title: "More") { (action, view, completion) in
completion(true)
self.delegate?.showMoreOptions(forStatus: self.statusID)
}
more.image = StatusTableViewCell.moreActionImage
more.backgroundColor = .gray
return UISwipeActionsConfiguration(actions: [reply, more])
}
}
extension StatusTableViewCell: AttachmentViewDelegate {
func showLargeAttachment(for attachmentView: AttachmentView) {
if let gifData = attachmentView.gifData {
delegate?.showLargeImage(gifData: gifData, description: attachmentView.attachment.description, animatingFrom: attachmentView)
} else {
delegate?.showLargeImage(attachmentView.image!, description: attachmentView.attachment.description, animatingFrom: attachmentView)
}
}
}
extension StatusTableViewCell: PreviewViewControllerProvider {
func getPreviewViewController(forLocation location: CGPoint, sourceViewController: UIViewController) -> UIViewController? {
if avatarImageView.frame.contains(location) {
return delegate?.router.profile(for: accountID)
} else if attachmentsView.frame.contains(location) {
let attachmentsViewLocation = attachmentsView.convert(location, from: self)
if let attachmentView = attachmentsView.subviews.first(where: { $0.frame.contains(attachmentsViewLocation) }) as? AttachmentView {
let image = attachmentView.image!
let description = attachmentView.attachment.description
return delegate?.largeImage(image, description: description, sourceView: attachmentView)
}
} else if contentLabel.frame.contains(location),
let vc = contentLabel.getViewController(forLinkAt: contentLabel.convert(location, from: self)) {
return vc
}
return delegate?.router.conversation(for: statusID)
}
}