Tusker/Tusker/Views/Notifications/ActionNotificationGroupTabl...

204 lines
7.3 KiB
Swift

//
// ActionNotificationGroupTableViewCell.swift
// Tusker
//
// Created by Shadowfacts on 9/5/19.
// Copyright © 2019 Shadowfacts. All rights reserved.
//
import UIKit
import Pachyderm
import SwiftSoup
class ActionNotificationGroupTableViewCell: UITableViewCell {
weak var delegate: TuskerNavigationDelegate?
var mastodonController: MastodonController! { delegate?.apiController }
@IBOutlet weak var actionImageView: UIImageView!
@IBOutlet weak var actionAvatarStackView: UIStackView!
@IBOutlet weak var timestampLabel: UILabel!
@IBOutlet weak var actionLabel: UILabel!
@IBOutlet weak var statusContentLabel: UILabel!
var group: NotificationGroup!
var statusID: String!
var avatarRequests = [String: ImageCache.Request]()
var updateTimestampWorkItem: DispatchWorkItem?
deinit {
updateTimestampWorkItem?.cancel()
}
override func awakeFromNib() {
super.awakeFromNib()
NotificationCenter.default.addObserver(self, selector: #selector(updateUIForPreferences), name: .preferencesChanged, object: nil)
}
@objc func updateUIForPreferences() {
let people = group.notificationIDs.compactMap(mastodonController.cache.notification(for:)).map { $0.account }
updateActionLabel(people: people)
for case let imageView as UIImageView in actionAvatarStackView.arrangedSubviews {
imageView.layer.cornerRadius = Preferences.shared.avatarStyle.cornerRadius(for: imageView)
}
}
func updateUI(group: NotificationGroup) {
guard group.kind == .favourite || group.kind == .reblog else {
fatalError("Invalid notification type \(group.kind) for ActionNotificationGroupTableViewCell")
}
self.group = group
guard let firstNotification = mastodonController.cache.notification(for: group.notificationIDs.first!) else { fatalError() }
let status = firstNotification.status!
self.statusID = status.id
updateUIForPreferences()
switch group.kind {
case .favourite:
actionImageView.image = UIImage(systemName: "star.fill")
case .reblog:
actionImageView.image = UIImage(systemName: "repeat")
default:
fatalError()
}
let people = group.notificationIDs.compactMap(mastodonController.cache.notification(for:)).map { $0.account }
actionAvatarStackView.arrangedSubviews.forEach { $0.removeFromSuperview() }
for account in people {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.layer.masksToBounds = true
imageView.layer.cornerRadius = Preferences.shared.avatarStyle.cornerRadiusFraction * 30
avatarRequests[account.id] = ImageCache.avatars.get(account.avatar) { [weak self] (data) in
guard let self = self, let data = data, self.group.id == group.id else { return }
DispatchQueue.main.async {
self.avatarRequests.removeValue(forKey: account.id)
imageView.image = UIImage(data: data)
}
}
actionAvatarStackView.addArrangedSubview(imageView)
NSLayoutConstraint.activate([
imageView.widthAnchor.constraint(equalToConstant: 30),
imageView.heightAnchor.constraint(equalToConstant: 30)
])
}
updateTimestamp()
updateActionLabel(people: people)
let doc = try! SwiftSoup.parse(status.content)
statusContentLabel.text = try! doc.text()
}
func updateTimestamp() {
guard let id = group.notificationIDs.first,
let notification = mastodonController.cache.notification(for: id) else {
fatalError("Missing cached notification")
}
timestampLabel.text = notification.createdAt.timeAgoString()
let delay: DispatchTimeInterval?
switch notification.createdAt.timeAgo().1 {
case .second:
delay = .seconds(10)
case .minute:
delay = .seconds(60)
default:
delay = nil
}
if let delay = delay {
if updateTimestampWorkItem == nil {
updateTimestampWorkItem = DispatchWorkItem { [weak self] in
self?.updateTimestamp()
}
}
DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: updateTimestampWorkItem!)
} else {
updateTimestampWorkItem = nil
}
}
func updateActionLabel(people: [Account]) {
let verb: String
switch group.kind {
case .favourite:
verb = "Favorited"
case .reblog:
verb = "Reblogged"
default:
fatalError()
}
let peopleStr: String
// todo: figure out how to localize this
// todo: update to use managed objects
switch people.count {
case 1:
peopleStr = people.first!.displayName
case 2:
peopleStr = people.first!.displayName + " and " + people.last!.displayName
default:
peopleStr = people.dropLast().map { $0.displayName }.joined(separator: ", ") + ", and " + people.last!.displayName
}
actionLabel.text = "\(verb) by \(peopleStr)"
}
override func prepareForReuse() {
super.prepareForReuse()
avatarRequests.values.forEach { $0.cancel() }
updateTimestampWorkItem?.cancel()
updateTimestampWorkItem = nil
}
}
extension ActionNotificationGroupTableViewCell: SelectableTableViewCell {
func didSelectCell() {
guard let delegate = delegate else { return }
let notifications = group.notificationIDs.compactMap(mastodonController.cache.notification(for:))
let accountIDs = notifications.map { $0.account.id }
let action: StatusActionAccountListTableViewController.ActionType
switch notifications.first!.kind {
case .favourite:
action = .favorite
case .reblog:
action = .reblog
default:
fatalError()
}
let vc = delegate.statusActionAccountList(action: action, statusID: statusID, statusState: .unknown, accountIDs: accountIDs)
delegate.show(vc)
}
}
extension ActionNotificationGroupTableViewCell: MenuPreviewProvider {
var navigationDelegate: TuskerNavigationDelegate? { return delegate }
func getPreviewProviders(for location: CGPoint, sourceViewController: UIViewController) -> PreviewProviders? {
return (content: {
let notifications = self.group.notificationIDs.compactMap(self.mastodonController.cache.notification(for:))
let accountIDs = notifications.map { $0.account.id }
let action: StatusActionAccountListTableViewController.ActionType
switch notifications.first!.kind {
case .favourite:
action = .favorite
case .reblog:
action = .reblog
default:
fatalError()
}
return self.delegate?.statusActionAccountList(action: action, statusID: self.statusID, statusState: .unknown, accountIDs: accountIDs)
}, actions: {
return []
})
}
}